gpt4 book ai didi

java - 求 5x5 数组的和

转载 作者:行者123 更新时间:2023-12-02 12:03:37 31 4
gpt4 key购买 nike

我的代码遇到问题。我试图找到这个 5x5 数组的总和,但它总是给我总计 0。当我使用 2x2 数组时,它可以工作,但对于 5x5 数组则不起作用。有人可以帮忙吗?

import java.util.*;

public class QuestionOne
{
public static void main(String[] args)
{
Random rand = new Random();
int num1=0, num2=0, num3=0, num4=0, num5=0;
int [][] numArray = new int [5][5];
int average =0, totalRow=0;
int highestVal=0, lowestVal=0;

for (int row = 0; row < 5; row++)
{
num1 = rand.nextInt(1000) + 1;
num4 =rand.nextInt(1000) + 1;
for (int col = 0; col < 4; col++)
{
num2 = rand.nextInt(1000) + 1;
num5 = rand.nextInt(1000) + 1;
}
num3 = rand.nextInt(1000) + 1;
System.out.println(num1+" " +num2+" " +num3 +" " +num4 +" " +num5);
}

//Sum all values
int total;
total =0;
for (int row = 0; row < numArray.length; row++)
{
for (int col = 0; col < numArray[row].length; col++)
{
total = total + numArray[row][col];
}
}

System.out.println("The total is " + total);
//System.out.println(numArray.length);

最佳答案

这里的问题是值没有设置到数组中,

请找到下面的工作代码。

public static void main(String[] args) {
Random rand = new Random();
int num1=0, num2=0, num3=0, num4=0, num5=0;
int [][] numArray = new int [5][5];
int average =0, totalRow=0;
int highestVal=0, lowestVal=0;

for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
num5 = rand.nextInt(1000) + 1;
numArray[row][col] = num5;
}
}

//Sum all values
int total;
total =0;
System.out.println(numArray.length);
for (int row = 0; row < numArray.length; row++)
{
for (int col = 0; col < numArray[row].length; col++)
{
total = total + numArray[row][col];
System.out.println("Row : " + row + "/Col : " + col);
System.out.println("Total : " + total + "/value : " + numArray[row][col]);
}
}

System.out.println("The total is " + total);

}

关于java - 求 5x5 数组的和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47066347/

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