嗨,我是java新手,并尝试做一些练习来熟悉它。我试图使用for each或enhanced for循环来计算用户输入数字的总和和平均值。我所做的是将数字存储在一个数组中。你能检查我的代码是否正确吗?
Scanner scanner = new Scanner(System.in);
double inputNum;
double sum= 0;
int counter;
System.out.println("How many entries would you like input");
int entry = scanner.nextInt();
for (counter = 0; counter< entry; counter++){
double [] numbers = new double[entry];
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
for (double x : numbers[counter]) {
x += sum;
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
}
答案 0 :(得分:1)
您不需要内循环。将每个输入存储在数组中后,可以将每个输入添加到总和中。
此外,您应该在外部循环外部分配一次数组,而不是在每次迭代中分配。
double [] numbers = new double[entry];
for (counter = 0; counter< entry; counter++){
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
sum+= numbers[counter];
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
答案 1 :(得分:0)
将总和和平均逻辑放在循环之外。这应该有效:
double [] numbers = new double[entry];
for (counter = 0; counter< entry; counter++){
System.out.println("Please input number " + (counter +1));
numbers[counter] = scanner.nextDouble();
sum += numbers[counter];
}
System.out.println("The total sum is: " + sum);
double average = sum/entry;
System.out.println("The total average is: " + average);
答案 2 :(得分:0)
您不能在扫描仪上使用for-each。此外,您无需存储任何东西。只需跟踪总和。
Scanner scanner = new Scanner(System.in);
System.out.println("How many entries would you like input?");
int numEntries = scanner.nextInt();
double sum = 0;
for (counter = 1; counter <= numEntries; counter++) {
System.out.println("Please input number " + counter + ": ");
sum += scanner.nextDouble();
}
System.out.println("The total sum is: " + sum);
System.out.println("The average is: " + sum / numEntries);
答案 3 :(得分:0)
相同的代码,循环外的平均值和删除无用的数组:
Scanner scanner = new Scanner(System.in);
double sum = 0;
System.out.println("How many entries would you like input");
int entry = scanner.nextInt();
for (int counter = 1; counter <= entry; counter++) {
System.out.println("Please input number " + counter);
sum += scanner.nextDouble();
}
System.out.println("The total sum is: " + sum);
double average = sum / entry;
System.out.println("The total average is: " + average);