gpt4 book ai didi

java - 为什么我无法获得矩阵元素的正确结果?

转载 作者:行者123 更新时间:2023-11-30 03:51:37 24 4
gpt4 key购买 nike

我想编写仅添加对角线元素的代码。

    import java.util.Scanner;

public class SabMat {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);
double [][] matrix = new double [4][4];

System.out.print("Enter matrix elements by row");
for (int i=0; i < matrix.length; i++) {
matrix[i][0] = input.nextDouble();
matrix[i][1] = input.nextDouble();
matrix[i][2] = input.nextDouble();
matrix[i][3] = input.nextDouble();
}

int total=0;
for (int row=0; row < matrix.length; row++) {
for (int column=0; column < matrix[row].length; column++) {
if (row == column){
total += total + matrix[row][column];
} else if (row!=column){
total = 0;
}
}
}

System.out.println("The sum of elements in the major diagonal is"+total);
}
}

结果不太好!问题是仅将 (3,3) 元素添加到总数中,而不是前三个元素。怎么解决这个问题?

最佳答案

您的代码不起作用,因为每次您偏离主对角线时它都会重置总数。

请注意,如果您只想对对角线的元素求和,则不需要两个循环:运行一个循环,而不是运行两个嵌套循环并等待 row == column,并对matrix[i][i]的值求和。

for (int i = 0 ; i != matrix.length ; i++) {
total += matrix[i][i];
}

关于java - 为什么我无法获得矩阵元素的正确结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24293113/

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