任务描述:
求一个3×3矩阵对角线元素之和,包括主对角线、副对角线元素和
(提示:主对角线: i==j,副对角线:i+j=2)。
解决思路:
定义 3*3 的二维数组,再输入9个数字,按照主对角线: i==j, 副对角线:i+j=2 的方法找对角线之和
代码示例:
package a4_2024_07;import java.util.Scanner;public class j240727_2 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);// 定义一个3x3的矩阵int[][] matrix = new int[3][3];// 从控制台读取矩阵的值System.out.println("请输入3x3矩阵的值:");for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {matrix[i][j] = scanner.nextInt();}}// 计算主对角线和副对角线元素之和int[] sums = calculateDiagonalSums(matrix);// 输出结果System.out.println("主对角线元素之和: " + sums[0]);System.out.println("副对角线元素之和: " + sums[1]);scanner.close();}private static int[] calculateDiagonalSums(int[][] matrix) {int mainDiagonalSum = 0;int secondaryDiagonalSum = 0;// 遍历矩阵for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {// 检查是否为主对角线元素if (i == j) {mainDiagonalSum += matrix[i][j];}// 检查是否为副对角线元素if (i + j == 2) {secondaryDiagonalSum += matrix[i][j];}}}return new int[]{mainDiagonalSum, secondaryDiagonalSum};}
}