第八章第一题(求矩阵中各列数字的和)(Find the sum of the numbers in each column of the matrix)
*8.1(求矩阵中各列数字的和)使用下面的方法头编写一个方法,求矩阵中特定列的所有元素的和:
public static double sumColumn(double[][] m,int columnIndex)
*8.1(Find the sum of the numbers in each column of the matrix)Use the following method header to write a method to sum all elements of a specific column in a matrix
public static double sumColumn(double[][] m,int columnIndex)
参考代码:
package chapter08;import java.util.Scanner;publicclassCode_01{publicstaticvoidmain(String[] args){double[][] matrix =newdouble[3][4];
Scanner input =newScanner(System.in);
System.out.println("Enter a 3-by-4 matrix row by row: ");for(int i =0;i <3;i++){for(int j =0;j <4;j++){
matrix[i][j]= input.nextDouble();}}for(int i =0;i <4;i++){
System.out.println("Sum of the elements at column "+ i +" is "+sumColumn(matrix,i));}}publicstaticdoublesumColumn(double[][] m,int columnIndex){double sum =0;for(int j =0;j <3;j++){
sum += m[j][columnIndex];}return sum;}}
结果显示:
Enter a 3-by-4 matrix row by row:1.52345.56789.5131
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0
Process finished with exit code 0