gpt4 book ai didi

java - 总结Java中的每一行和每一列

转载 作者:行者123 更新时间:2023-11-29 07:50:29 24 4
gpt4 key购买 nike

/*
* Programmer: Olawale Onafowokan
* Date: February 6, 2014
* Purpose: Prints the row and column averages
*/
class Lab4 {
public static void main(String[] args) {
int [][] scores = {{ 20, 18, 23, 20, 16 },
{ 30, 20, 18, 21, 20 },
{ 16, 19, 16, 53, 24 },
{ 25, 24, 22, 24, 25 }};
outputArray(scores);
}

public static void outputArray(int[][] array) {
int sum= 0;
int rowSize = array.length;
int columnSize = array[0].length;
System.out.println("rows=" + rowSize + "cols=" + columnSize);

for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
sum += array[i][j];
}
System.out.println("Print the sum of rows = " + sum);
}
for (int i = 0; i < array.length; i++) {
sum = 0;
sum = sum + array[i][j];
// It is telling me the j can't be resolved
}
}
}

程序打印出:

rows=4cols=5
Print the sum of rows = 612
Print the sum of rows = 20358
Print the sum of rows = 652058
Print the sum of rows = 20866609

我不明白为什么它没有正确地添加数字。我正在尝试将每一行和每一列相加。我什至不确定这些数字是从哪里来的。

最佳答案

这是你的问题:

sum += sum + array[i][j];

sum += sum + array[i][j]sum = sum + sum + array[i][j] 相同(你加了两次 sum)

应该是:

sum = sum + array[i][j]; 或者 sum += array[i][j];

如果您只想打印每个的总和,请将您的sum重置为0,以便在外部上进行每次迭代-循环

for (int i = 0; i < array.length; i++){
sum=0;
....

如果你只想打印每个的总和,你需要添加:

int[] colSum =new int[array[0].length];  

然后在 for-loop 中,添加

colSum[j]+=array[i][j]; 

最后你会得到这个:

int[] colSum =new int[array[0].length];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
sum += array[i][j];
colSum[j] += array[i][j];
}
System.out.println("Print the sum of rows =" + sum);
}
for(int k=0;k<colSum.length;k++){
System.out.println("Print the sum of columns =" + colSum[k]);
}

关于java - 总结Java中的每一行和每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com