我试图编写一个方法来计算双精度数组中的值的平均值,但我无法获得要打印的平均值。它编译并执行,但不返回任何结果。
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;
}
}
发布于 2019-04-16 06:35:50
您将从for循环中返回total。这就是为什么它不打印任何东西的原因。注释来自for循环的return total语句,它会正确地打印平均值。
发布于 2019-04-16 06:37:28
return total; // delete that
它使你脱离了你的方法。
发布于 2019-04-16 07:13:59
嗯,我看到在主代码中没有任何东西,这就是为什么它编译但没有显示结果的原因。您必须在main
中调用该方法,但删除参数double[]x
,因为您没有使用它。
https://stackoverflow.com/questions/55698032
复制相似问题