有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算最小值与计算最大值

我怀疑我在编写“lowestScore”方法时出错(我或多或少否定了“largestScore”方法,因为该方法始终返回正确的值(数组中的最高分数)。但出于某种原因,我的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) 个答案

  1. # 1 楼答案

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

    改变

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

    for (int i=0; i < scores.length; i++)
    
  2. # 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时,它永远不会大于数组的大小。因此,循环立即结束,返回值是数组的第一个元素,如循环之前设置的

    另外,很容易否认错误,你只是在把highestScore改成lowestScore时把<>倒过来