gpt4 book ai didi

java - 没有得到矩阵JAVA主对角线所需的输出

转载 作者:行者123 更新时间:2023-12-02 13:24:06 24 4
gpt4 key购买 nike

该程序应该:“向用户询问数字 n。创建一个 nxn 整数矩阵。使用 5 的种子用 0 到 9 之间的随机数填充矩阵(请记住,当我们播种随机数生成器时,我们会得到可预测的“随机”数字)。

对于满分,计算从矩阵左上角开始的对角线之和(索引 [0][0])。将总数显示到屏幕上。”

教授回答:“对于 100 x 100 矩阵,主对角线的总和应为 503,另一对角线的总和应为 444。”

我的程序答案:700 主对角线。所以我猜测我的 MakeandFillMatrix 方法有问题。

import java.util.*;
/*

*/
public class TesterProject
{
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);
printMatrix(m);

int sumD1 = calculateMainDiagonal(m);
System.out.println("The sum of the main diagonal is " + sumD1);
}
public static int getMatrixSize()
{
Scanner S = new Scanner(System.in);

System.out.println("give me a int to create the matrix");
while(!S.hasNextInt())
{
System.out.println("I need an integer!");
S.next();
}
int n = S.nextInt();
return n;
}
public static int [][] makeAndFillMatrix(int n)
{
Random generator = new Random(5);
int [][] r = new int[n][n];
int rand = generator.nextInt(10);

for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
r[i][j] = rand;
//rand++;
}
}
return r;
/*
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r[i].length; j++)
{
r[i][j]= rand;
}
}
return r;
*/
}
public static void printMatrix(int [][] matrix)
{
for(int r = 0; r < matrix.length; r++)
{
for(int c = 0; c < matrix[r].length; c++)
{
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
public static int calculateMainDiagonal(int [][] m)
{
int total = 0;
for (int r = 0; r < m.length; r++)
{
total += m[r][r];
}
return total;
}
}

最佳答案

您的问题是您只生成一次随机数。无论如何,你都会看到你的矩阵仅由 7 个组成。当您编写 r[i][j] = rand 时,您确实应该将该元素设置为新的随机数。删除 rand = Generator.nextInt(10) 行,并将前面提到的行更改为 r[i][j] = Generator.nextInt(10)

关于java - 没有得到矩阵JAVA主对角线所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443418/

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