[英]How can I get the average of a 2D array
I have a current method that is supposed to display the average of a 2D but it is outputting numbers that don't make sense For example;我有一个当前方法应该显示 2D 的平均值,但它输出的数字没有意义例如; the average of 1.0,2.0,3.0,4.0,5.0,6.0 is 3.5 but my program is outputting the average as 10.5 for the numbers above.
1.0,2.0,3.0,4.0,5.0,6.0 的平均值为 3.5,但我的程序将上述数字的平均值输出为 10.5。
Here is my method below下面是我的方法
public static double getAverage(double[][] array1) {
double total = 0; //Accumulator
int num = 0;
for(int row = 0; row < array1.length; row++)
{
for(int col =0; col < array1[row].length; col++)
total += array1 [row][col];
num += 1;
}
return total / num;
}
A simple version would be一个简单的版本是
public static double getAverage(double[][] a) {
return Arrays.stream(a)
.flatMapToDouble(Arrays::stream)
.average()
.orElseThrow(() -> new IllegalArgumentException("no elements in the array"));
}
Your mistake is that you increment num
in the row
loop while you should do it inside the col
loop.您的错误是您
row
循环中增加num
而您应该在col
循环中执行此操作。
A fun version would be一个有趣的版本将是
for (int row = 0; row < array1.length; row++)
for (int col = 0; col < array1[row].length; total += array1[row][col++], num++);
You'r num
variable is counting the numbers of rows and not the number of cells like it supposed to.您的
num
变量正在计算行数,而不是应该计算的单元格数。
try instead of尝试代替
for(int col =0; col < array1[row].length; col++)
total += array1 [row][col];
num += 1;
to do this:去做这个:
for(int col =0; col < array1[row].length; col++) {
total += array1 [row][col];
num += 1;
}
[I have deleted a mistake that i wrote here] [我已经删除了我在这里写的一个错误]
Change num += 1;
改变
num += 1;
to至
num += array1[row].length;
You're incrementing num inside the outer loop.您在外循环内增加 num 。 You need to increment it in the inner loop for it to work as you expect:
您需要在内部循环中增加它才能按预期工作:
public static double getAverage(double[][] array1)
{
double total = 0; //Accumulator
int num = 0;
for(int row = 0; row < array1.length; row++)
{
for(int col =0; col < array1[row].length; col++) {
total += array1 [row][col];
num += 1;
}
}
return total / num;
}
A word of advice - just default to putting braces around your for loops.一个忠告 - 只是默认在你的 for 循环周围放置大括号。 There's no point in risking bugs in order to save a couple of lines in your program.
为了在程序中保存几行代码而冒着 bug 的风险是没有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.