第八章第一题(求矩阵中各列数字的和)(Find the sum of the numbers in each column of the matrix)

该博客展示了如何编写一个Java方法来计算二维矩阵中特定列的所有元素之和。提供的代码示例创建了一个3x4的矩阵,并从用户那里获取输入,然后逐列计算并打印出每列的总和。程序运行示例显示了每列元素的求和结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第八章第一题(求矩阵中各列数字的和)(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;

public class Code_01 {
    public static void main(String[] args) {
        double[][] matrix = new double[3][4];
        Scanner input = new Scanner(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));
        }
    }
    public static double sumColumn(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.5 2 3 4 
5.5 6 7 8
9.5 1 3 1
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值