gpt4 book ai didi

java - 矩阵列和java

转载 作者:行者123 更新时间:2023-12-02 11:50:04 25 4
gpt4 key购买 nike

我最近才开始使用 Java。我仍然在 Java 方面遇到一些困难。任务是分别对列和行求和,示例如下所示。我设法获得了列的总和,但最终总是在我想要的输出中重复第一行,如何删除该错误。只需要所需的列总和即可。

它如何分别计算行的总和?

非常感谢您提前提供的帮助

代码如下所示:

public class MatrixColumnSums {

public static void main(String[] args) {
// TODO Auto-generated method stub

double [][] a = new double [2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;

System.out.println( "A");
for (int i = 0; i < a.length; i++) {
String str = "";
for (int j = 0; j < a[i].length; j++) {
str += a[i][j] + "\t";
}
System.out.println(str);
}
// column sums
// creating another matrix to store the sum of columns matrices
double c[] = new double [a[0].length];

// Adding and printing addition of 2 matrices
System.out.println("C");

for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
{
c[j] += a[i][j];

System.out.print(c[j] + "\t");

}
System.out.println();
}

}
}

输出如下所示:

A

1.0 2.0 3.0

4.0 5.0 6.0

C

1.0 2.0 3.0 ( <= I want to get this row deleted)

5.0 7.0 9.0 ( I just want to have this as my output)

最佳答案

**矩阵列总和**

doOneColumnSum 方法对一列求和。

 private static double doOneColumnSum(double[][] arr, int col){

double total = 0;
for (int row = 0; row < arr.length; row += 1){
total += arr[row][col];
}
return total;
}

doColumnSums 方法使用 doOneColumnSum 方法对所有列求和

public static double[] doColumnSums(double[][] arr)
{
int numColumns = arr[0].length;
double[] result = new double[numColumns];
for (int col = 0; col < numColumns; col += 1)
{
result[col] = findOneColumnSum(arr, col);
}
return result;
}

关于java - 矩阵列和java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com