gpt4 book ai didi

java - 如何比较各行的总和?

转载 作者:行者123 更新时间:2023-12-02 10:15:41 25 4
gpt4 key购买 nike

我已经成功编写了将一行中的数字相加的代码,但现在我只能比较不同行的总和。什么样的代码比较数组行的总和?

我想尝试一个 if 语句,但是一旦我到达它,我不知道如何获取不同的行然后进行比较,因为你不能真正执行 sum > sum

public class MatrixLab {

public int largestRowSum(int[][] matrix) {
//Comment outline before coding!
int[][] nums = matrix;
int sum = 0;
int arraySum = 0;
//add individual rows
for(int r = 0; r < matrix.length; r++) {
for(int c = 0; c < matrix[r].length; c++) {
sum += nums[r][c];
}
}
System.out.println( sum );
//compare rows

//return the value
System.out.println( arraySum );
}

需要返回比较行后具有最大值的行的索引

最佳答案

保留一个变量来指示到目前为止最大的总和,以及是否还想存储索引

 public int largestRowSum(int[][] matrix) {
//Comment outline before coding!
int[][] nums = matrix;
int sum = 0;
int arraySum = 0;
int maxSum = 0; // Indicates the max sum of row encountered till now
int indexOfmaxSumRow = 0; // index of row which corresponds to maxsum
//add individual rows
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
sum += nums[r][c];
}
if (sum > maxSum) {
maxSum = sum;
indexOfmaxSumRow = r;
}
}
System.out.println(sum);
//compare rows

//return the value
System.out.println(arraySum);
return indexOfmaxSumRow;
}

关于java - 如何比较各行的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54703723/

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