gpt4 book ai didi

Java,行和列的总和

转载 作者:行者123 更新时间:2023-12-01 17:42:26 26 4
gpt4 key购买 nike

您好,我正在尝试计算矩阵的每一行和每一列的总和,然后打印最小值的总和。现在我遇到了一个问题。我得到的“smallRows”总和不是矩阵中的最小行。这只是最新的。我该如何改进这个?提前致谢!

    {
int rows = 4;
int columns = 5;
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
matrix[i][j] = new Random().nextInt(9) + 1;
}
}
printMatrix(matrix);
int[] tempRows = new int[columns];
int[] smallRows = new int[columns];

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
tempRows[j] = matrix[i][j];
}

if(sum(smallRows) == 0)
{
smallRows = tempRows;
}
if (sum(tempRows) < sum(smallRows))
{
smallRows = tempRows;
}
}
}
public static int sum(int[] a)
{
int sum = 0;
for (int i = 0; i < a.length; i++)
{
sum += a[i];
}
return sum;
}
public static void printMatrix(int mat[][])
{
for (int[] row : mat)
System.out.println(Arrays.toString(row));
}

最佳答案

以下是如何找出最小值及其索引以及它是来自行还是列

int smallest = Integer.MAX_VALUE;
int indexOfSmallest = -1;
boolean isRow = true;

for (int i = 0; i < rows; i++) {
int value = sum(matrix[i]);
if (value < smallest) {
smallest = value;
indexOfSmallest = i;
}
}
for (int i = 0; i < columns; i++) {
int columnSum = 0;
for (int j = 0; j < rows; j++) {
columnSum += matrix[i][j];
}
if (columnSum < smallest) {
smallest = columnSum;
indexOfSmallest = i;
isRow = false;
}
}

之后,您可以打印 indexOfSmallestisRow 指向的最小值的行或列。

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

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