第八章第二题(求矩阵主对角线元素的和)(Finding the sum of the main diagonal elements of a matrix)
*8.2(求矩阵主对角线元素的和)使用下面的方法头编写一个方法,求nxn的double类型矩阵中主对角线上所有数字的和: public static double sumMajorDiagonal(double[][] m) 编写一个测试程序,读取一个4x4的矩阵,然后显示他的主对角线上的所有元素的和。下面是一个运行示例: Enter a 4-by-4 matrix row by row: 1 2 3 4.0 5 6.5 7 8 9 10 11 12 13 14 15 16 Sum of the elements in the major diagonal is 34.5 *8.2(Finding the sum of the main diagonal elements of a matrix)Use the following method header to write a method to find the sum of all the numbers on the main diagonal in the double type matrix of NxN: public static double sumMajorDiagonal(double[][] m) Write a test program, read a 4x4 matrix, and then display the sum of all elements on its main diagonal. Here is a running example: Enter a 4-by-4 matrix row by row: 1 2 3 4.0 5 6.5 7 8 9 10 11 12 13 14 15 16 Sum of the elements in the major diagonal is 34.5
参考代码:
package chapter08;import java.util.Scanner;publicclassCode_02{publicstaticvoidmain(String[] args){double[][] m =newdouble[4][4];
Scanner input =newScanner(System.in);
System.out.println("Enter a 4-by-4 matrix row by row: ");for(int i =0;i <4;i++)for(int j =0;j <4;j++)
m[i][j]= input.nextDouble();
System.out.println("Sum of the elements in the major diagonal is "+sumMajorDiagonal(m));}publicstaticdoublesumMajorDiagonal(double[][] m){double sum =0;for(int i =0;i < m.length;i++)
sum += m[i][i];return sum;}}
结果显示:
Enter a 4-by-4 matrix row by row:1234.056.578910111213141516
Sum of the elements in the major diagonal is 34.5
Process finished with exit code 0