【问题标题】:Code will not print average for array of doubles [closed]代码不会打印双精度数组的平均值 [关闭]
【发布时间】:2019-04-15 22:26:04
【问题描述】:

试图编写一个计算双精度数组中值的平均值的方法,但我无法得到要打印的平均值。它编译并执行,但不返回任何结果。

public class Test3Q1 {
    public static void main(String[] args) {
    }

    public static double average (double[]x) {
        double [] doubleValues = {3.0, 10.5, 19.8, 5.6, 3.2};
        double total = 0.0;
        for (int i =0; i<doubleValues.length; i++) {
        total += doubleValues[i];
        return total; }
        double average = total/doubleValues.length;


        System.out.println("The average of the doubles Array 
                               is: " + average);
        System.out.format("The average of the double array is: 
                             %.1f", average);
        return average;
    }
}

【问题讨论】:

  • 你为什么要返回循环内?
  • 您也传递了double[] x,但没有在方法中使用它。
  • 而且您的 main 方法也永远不会调用 average
  • 你里面有一个return for sentence。您没有遍历数组并且 println 没有执行。

标签: java arrays printing average


【解决方案1】:

这对我来说就像一个家庭作业问题,但我认为这样的事情应该可以解决你的问题。

public class Test3Q1 {
    public static void main(String[] args) {
        double [] doubleValues = {3.0, 10.5, 19.8, 5.6, 3.2};

        double avg = average(doubleValues);

        System.out.println("The average of the doubles Array is: " + avg);
        System.out.format("The average of the double array is: %.1f", avg);
    }

    public static double average (double[] values) {
        double total = 0.0;

        for (int i =0; i<values.length; i++) {
            total += values[i];
        }

        return total/values.length;
    }
}

请注意,在这种情况下,您不应在 for 循环中使用 return我还从average 方法参数中删除了您的double[] x,因为在这种情况下不需要它。 我已经编辑了答案以再次包含参数double[] values,因为它使方法更通用,因为您现在可以插入任何doubles 数组。

【讨论】:

  • 为什么不将double[] x 保留为参数并将doubleValues 数组移动到main,以便该方法可重用于计算其他输入的其他平均值?
  • @Eritrean 我曾想过这样做,但我不确定他的要求是什么。我会更新答案。
【解决方案2】:

您正在从 for 循环中返回总计。这就是为什么它不打印任何东西。 注释 for 循环中的 return total 语句,它会正确打印平均值。

【讨论】:

  • 害怕循环中的返回不是唯一的问题。见上面的 cmets。
【解决方案3】:
return total; // delete that

它让你脱离了你的方法。

【讨论】:

    【解决方案4】:

    好吧,我看到主代码中没有任何内容,这就是它编译但没有显示结果的原因。您必须调用main 中的方法,但删除参数double[]x 因为您没有使用它。

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多