我想写一个java程序,打印二维数组每行的平均值,但它只适用于第一行。我不知道问题出在哪里。
这是代码:
int [][] A = new int[r][c];
for (int i=0;i<A.length;i++)
{
System.out.println("Enter the elements of the row number: "+(i+1));
for (int j=0; j<A[i].length;j++)
A[i][j]=kbd.nextInt();
}
int sum = 0, avg =0;
for (int i=0; i<A.length;i++)
{
for (int j=0; j<A[i].length;j++) {
sum += A[i][j];
avg = sum/A[i].length;
}
System.out.println("The average of the row number: "+(i+1)+" is: "+avg);
}
}
每次循环时都需要将sum重置为零。这可以通过在for循环内部而不是外部声明sum变量来解决。此外,avg和sum应该是双精度,而不是int:
for (int i=0; i<A.length;i++)
{
double sum = 0;
double avg =0;
for (int j=0; j<A[i].length;j++) {
sum += A[i][j];
avg = sum/A[i].length;
}
System.out.println("The average of the row number: "+(i+1)+" is: "+avg);
}
我认为问题可能出在sum值上,您不能在计算下一行的sum之前删除值。此外,我认为在打印之前可以在循环之后计算平均值。
int sum = 0, avg =0;
for (int i=0; i<A.length;i++)
{
sum = 0;
for (int j=0; j<A[i].length;j++) {
sum += A[i][j];
}
avg = sum/A[i].length;
System.out.println("The average of the row number: "+(i+1)+" is: "+avg);
}
for (int i=0; i<A.length;i++)
{
double sum = 0;
double avg =0;
for (int j=0; j<A[i].length;j++) {
sum += A[i][j];
avg = sum/A[i].length;
}
System.out.println("The average of the row number: "+(i+1)+" is: "+avg);
}
当然,您也可以使用lambda并从一开始就避免这样的问题
for(int row = 0; row < A.length; row++) {
double avg = Arrays.stream(A[row]).boxed().collect(averagingInt(i -> i));
System.out.println("The average of the row number: " + (row + 1) + " is: " + avg);
}