以下是原始问题:
编写一个程序,声明一个名为得分的二维二维数组,包含三行三列。使用嵌套的while循环在命令行中从用户获取九(3 x 3)个双精度数。最后,使用嵌套for循环计算每行中双精度的平均值,并将这三个平均值输出到命令行。
这是我的代码:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
我现在编辑了代码,以在底部显示我的新嵌套for循环。这些应该计算输入数字的平均值,但是,我不确定为什么它不起作用?
答案 0 :(得分:1)
这种逻辑很奇怪,永远无法满足
while (count < 3) {
while (count < 9) {
当计数大于3时,您将永远不会再看到count<9
你应该再考虑并重新排序该值的条件检查..
while (count < 9) {
while (count < 3) {
可能更有意义......
答案 1 :(得分:1)
您可以使用两个变量,一个用于行,另一个用于列:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
答案 2 :(得分:0)
您可以重写此细分:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...至
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
...同时填充矩阵并计算均值。
答案 3 :(得分:0)
或者你可以有一个循环;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
答案 4 :(得分:0)
首先考虑英语或伪代码,这将会非常容易。
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
代码:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
如果你能得到一行的平均值,恭喜你,你的工作已经完成了一半以上。只需使用另一个循环对所有其他行重复上述过程。 (这解释了为什么你需要2个循环。一个用于列,另一个用于行)。
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
代码:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
从row
和col
获取值
int row = scores.length;
int col = scores[0].length;