我想知道如何在2D数组中打印每一行的总和 循环进行时对每一行求和的方法。
int sum = 0;
int[][] nums = {{16, 29, 31, 65, 67},
{28, 30, 39, 59, 70},
{1, 42, 47, 64, 70}};
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
sum+= nums[i][j];
}
System.out.println(Arrays.toString(nums[i]));
System.out.println(sum);
}
答案 0 :(得分:0)
如果要打印每行的总和,则每次开始对新行求和时都需要将sum
重置为0。
int[][] nums = {{16, 29, 31, 65, 67}, {28, 30, 39, 59, 70}, {1, 42, 47, 64, 70}};
for (int row = 0; row < nums.length; row++) {
int sum = 0;
for (int col = 0; col < nums[row].length; col++)
sum += nums[row][col];
System.out.println(Arrays.toString(nums[row]));
System.out.println(sum);
}