第八章第二题(求矩阵主对角线元素的和)(Finding the sum of the main diagonal elements of a matrix)

该程序实现了一个方法来计算一个4x4矩阵主对角线元素的总和,并通过用户输入来测试该功能。用户逐行输入矩阵,程序计算并显示主对角线元素的和。例如,给定矩阵1234.0 56.578 9101112 13141516,主对角线元素的和为34.5。
摘要由CSDN通过智能技术生成

第八章第二题(求矩阵主对角线元素的和)(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;

public class Code_02 {
    public static void main(String[] args) {
        double[][] m = new double[4][4];
        Scanner input = new Scanner(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));
    }
    public static double sumMajorDiagonal(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: 
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

Process finished with exit code 0

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值