列的二维数组总和 [英] two dimensional array sum of columns
问题描述
我有一个二维数组,如下所示:
I have two dimensional array as below:
[33] [96] [34] [11] [65] [68] [12] [8] [= 327]
[33] [96] [34] [11] [65] [68] [12] [8 ] [=327]
[94] [91] [3] [20] [16] [59] [74] [97] [= 454]
[94] [91] [3 ] [20] [16] [59] [74] [97] [=454]
[29] [0] [31] [13] [4] [63] [52] [73] [= 265]
[29] [0 ] [31] [13] [4 ] [63] [52] [73] [=265]
[51] [3] [55] [74] [52] [79] [61] [74] [= 449]
[51] [3 ] [55] [74] [52] [79] [61] [74] [=449]
[18 ] [19] [1] [53] [33] [93] [26] [14] [= 257]
[18] [19] [1 ] [53] [33] [93] [26] [14] [=257]
[56] [41] [4] [16] [45] [8] [57] [22] [= 249]
[56] [41] [4 ] [16] [45] [8 ] [57] [22] [=249]
[43] [33] [43] [59] [61] [ 58] [58] [69] [= 424]
[43] [33] [43] [59] [61] [58] [58] [69] [=424]
[38] [41] [42] [29] [27] [72] [85] [75 ] [= 409]
[38] [41] [42] [29] [27] [72] [85] [75] [=409]
[36] [3] [23] [65] [40] [56] [41] [96] [= 36]
[36] [3 ] [23] [65] [40] [56] [41] [96] [=36]
[=?] [=?] [=?] [=?] [=?] [=?] [=?] [=?]
[=?] [=?] [=?] [=?] [=?] [=?] [=?] [=?]
如何获取数组中列的总和?
how to get the sum of the columns in the array?
这是我获取行总和的代码:
here is my code to get the sum of the rows:
public static void main(String[] args) {
int[][] nums = new int[9][9];
int random, total_rows=0, total_cols=0;
Random randomGenerator = new Random();
for (int i=0; i < 9; i++) {
for (int j=0; j < 9; j++) {
random = randomGenerator.nextInt(100);
nums[i][j] = random;
if(j < 8) {
total_rows += random;
}else {
System.out.print("=");
nums[i][j] = total_rows;
total_rows = 0;
}
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
推荐答案
您可以尝试:
int[][] num = new int[9][9];
/*
* ...populate the array
*
*/
for (int i = 0; i < num.length; i++) {
int sum = 0;
for (int j = 0; j < num[i].length; j++) {
sum += num[j][i];
}
System.out.println(sum);
}
这篇关于列的二维数组总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!