计算最小值与计算最大值

时间:2013-05-07 14:21:11

标签: java for-loop

我怀疑在编写“最低分数”方法时我犯了一个错误(我或多或少地否定了我的“最大分数”方法,因为它一直返回正确的值(数组中的最高分)。但由于某种原因,我的lowestScore方法要么只返回数组中的第一个元素,要么返回一些任意数字,甚至不是数组。任何想法?

    public static double highestScore(double[] scores)
    {
      double max = scores[0];
      for (int i=0; i < scores.length; i++) {
        if (scores[i] > max) {
          max = scores[i];
        }
      }
      return max;
    }

    public static double lowestScore(double[] scores)  //possible problem some where in
    {                                                  //here?
      double min = scores[0];
      for (int i=0; i > scores.length; i++) {
        if (scores[i] < min) {
          min = scores[i];
        }
      }
      return min;
    }

2 个答案:

答案 0 :(得分:6)

是的,问题出在lowestScore。你倒转了<>,但你仍然应该遍历整个数组。在您的代码中,i > scores.length(最初为0 > scores.length)的计算结果为false,因此循环不会执行,min始终等于scores[0]。< / p>

更改

for (int i=0; i > scores.length; i++)

for (int i=0; i < scores.length; i++)

答案 1 :(得分:2)

public static double lowestScore(double[] scores)  //possible problem some where in
{                                                  //here?
  double min = scores[0];
  for (int i=0; i > scores.length; i++) {
    if (scores[i] < min) {
      min = scores[i];
    }
  }
  return min;
}

for (int i=0; i > scores.length; i++) {行。条件是“如果i大于scores.length,则继续循环”。当i现在初始化为0时,它永远不会大于数组的大小。因此,循环立即结束,返回值是数组的第一个元素,如循环之前设置的那样。

P.S。在将<更改为>时,您只是忽略了highestScorelowestScore s。

相关问题