编写一个 Java 程序,通过示例查找矩阵的每一列之和。或者 Java 程序计算给定多维数组或矩阵中每一列的总和。
在这个 Java 矩阵列求和示例中,我们声明了一个具有随机值的 3*3 整型 SumOfCols_arr 矩阵。接下来,我们使用 for 循环迭代 SumOfCols_arr 矩阵的项。在 for 循环中,我们正在计算矩阵列的总和。
public class SumOfMatrixColumns {
public static void main(String[] args) {
int i, j, sum;
int[][] SumOfCols_arr = {{11, 21, 31}, {41, 51, 61}, {71, 81, 91}};
for(i = 0; i < SumOfCols_arr.length; i++)
{
sum = 0;
for(j = 0; j < SumOfCols_arr[0].length; j++)
{
sum = sum + SumOfCols_arr[j][i];
}
System.out.println("\nThe Sum of Matrix Items "
+ "in Column " + i + " = " + sum);
}
}
}

Java 程序查找矩阵的每一列之和 示例 2
这个用于矩阵每列求和的 Java 代码与上面提到的相同。但是,这个 Java 代码允许用户输入行数、列数和 矩阵项。请参阅 C 程序查找矩阵的每一列之和文章以了解迭代式 for 循环的执行。
import java.util.Scanner;
public class SumOfMatrixColumns {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, sum = 0;
sc= new Scanner(System.in);
System.out.println("\n Enter Matrix Rows and Columns : ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] SumOfCols_arr = new int[rows][columns];
System.out.println("\n Please Enter the Matrix Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
SumOfCols_arr[i][j] = sc.nextInt();
}
}
for(i = 0; i < SumOfCols_arr.length; i++)
{
sum = 0;
for(j = 0; j < SumOfCols_arr[0].length; j++)
{
sum = sum + SumOfCols_arr[j][i];
}
System.out.println("\nThe Sum of Matrix Items "
+ "in Column " + i + " = " + sum);
}
}
}
矩阵列的输出
Enter Matrix Rows and Columns :
3 3
Please Enter the Matrix Items :
10 20 30
12 22 33
130 40 50
The Sum of Matrix Items in Column 0 = 152
The Sum of Matrix Items in Column 1 = 82
The Sum of Matrix Items in Column 2 = 113