gpt4 book ai didi

java - 平均二维数组列

转载 作者:行者123 更新时间:2023-11-30 05:25:18 25 4
gpt4 key购买 nike

我正在尝试对二维数组列进行平均。我的代码似乎将行中的数字相加,然后除以总数。在这个例子中应该只有 4 次赋值,但它循环了 12 次。有人知道我的代码有什么问题吗?这些数字是从文本文件输入的,位于完整代码的较高位置(不确定这是否会影响它)。

数组示例:

[2,3,6,7]
[4,5,6,7]
[2,2,2,2]
System.out.println("Average score of each assignment:");
//TODO: compute and print the average on each assignment
double total = 0;
int totallength = 0;
int assignment = 1;
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
total += myArray[i][j];
totallength++;
System.out.println("Assignment #" + assignment++
+ " Average: " + (total / totallength));
}
}

这是我的输出:

Average score of each assignment:
Assignment #1 Average: 2.0
Assignment #2 Average: 2.5
Assignment #3 Average: 3.6666666666666665
Assignment #4 Average: 4.5
Assignment #5 Average: 4.4
Assignment #6 Average: 4.5
Assignment #7 Average: 4.714285714285714
Assignment #8 Average: 5.0
Assignment #9 Average: 4.666666666666667
Assignment #10 Average: 4.4
Assignment #11 Average: 4.181818181818182
Assignment #12 Average: 4.0

期望的输出:

Assignment #1 Average: 2.666666666
Assignment #2 Average: 3.333333333
Assignment #3 Average: 4.666666666
Assignment #4 Average: 5.333333333

最佳答案

您可以按如下方式进行:

public class Main {
public static void main(String[] args){
int [][]myArray= {
{2,3,6,7},
{4,5,6,7},
{2,2,2,2},
};
double total=0;
int assignment=1;

System.out.println("Average score of each assignment:");
for(int i=0;i<myArray[0].length;i++) {
for(int j=0;j<myArray.length;j++) {
total+=myArray[j][i];
}
System.out.println("Assignment #" + assignment++ + " Average: " + (total/3));
total=0;
}
}
}

输出:

Average score of each assignment:
Assignment #1 Average: 2.6666666666666665
Assignment #2 Average: 3.3333333333333335
Assignment #3 Average: 4.666666666666667
Assignment #4 Average: 5.333333333333333

关于java - 平均二维数组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58793511/

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