我试图在二维数组中找到总和最小的行,但我只得到 0
I try to find the row with the minimum sum in a 2D array but I only get 0
为什么我得到的 minRow 和 minRowIndex 为 0?谢谢谁回复。
import java.util.Scanner;
public class test1 {
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
int [][] matrix = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}};
int minRow = 0;
int minRowAvg = 0;
int minRowIndex = 0;
for (int row = 1; row < matrix.length; row++){
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++){
rowSum += matrix[row][col];
}
if (rowSum < minRow && rowSum > 0){
minRow = rowSum;
minRowIndex = row;
}
}
System.out.println("Row " + minRowIndex + " has the minimum sum of " + minRow);
}
}
rowSum
永远不会小于 minRow
,因为您将 minRow
初始化为 0。
您应该将其初始化为 Integer.MAX_VALUE
。
int minRow = Integer.MAX_VALUE;
首先,在你的第一个循环中,行变量从 1 开始,所以你永远不会检查你的第一个矩阵行,它应该从 0 开始。
您的 minRow 初始化为 0,仅在您的
中修改
if (rowSum < minRow && rowSum > 0){
minRow = rowSum;
minRowIndex = row;
}
您的条件始终为假,因为 rowSum 始终优于 minRow。这与您的 minRowIndex 存在相同的问题。
为什么我得到的 minRow 和 minRowIndex 为 0?谢谢谁回复。
import java.util.Scanner;
public class test1 {
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
int [][] matrix = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}};
int minRow = 0;
int minRowAvg = 0;
int minRowIndex = 0;
for (int row = 1; row < matrix.length; row++){
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++){
rowSum += matrix[row][col];
}
if (rowSum < minRow && rowSum > 0){
minRow = rowSum;
minRowIndex = row;
}
}
System.out.println("Row " + minRowIndex + " has the minimum sum of " + minRow);
}
}
rowSum
永远不会小于 minRow
,因为您将 minRow
初始化为 0。
您应该将其初始化为 Integer.MAX_VALUE
。
int minRow = Integer.MAX_VALUE;
首先,在你的第一个循环中,行变量从 1 开始,所以你永远不会检查你的第一个矩阵行,它应该从 0 开始。
您的 minRow 初始化为 0,仅在您的
中修改if (rowSum < minRow && rowSum > 0){
minRow = rowSum;
minRowIndex = row;
}
您的条件始终为假,因为 rowSum 始终优于 minRow。这与您的 minRowIndex 存在相同的问题。