我无法让代码显示四个平均值的最高平均值,我似乎只得到最后的平均分数,并且填写了最高的平均值,这不是最高分。
这是我的代码:
import java.io.*;
import java.util.*;
class Bowling Scores
{
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
int G =0;
int scores = 0;
double avg = 0;
double highest_average=0;
int times = 0;
int players = 4;
for(int i =1; i<=players; i++) {
System.out.println("Player " + i);
if (avg > highest_average)
highest_average= avg;
do
{
System.out.println("Enter your bowling score:");
G = keyboard.nextInt();
scores += G;
times++;
}
while((G !=-1)); // -1 is what makes the loop end for the current player, a total of four players will get an average after -1 is inputted
scores += + 1;
times = times - 1;
avg = (scores)/(times);
System.out.printf("Average= %.2f\n", avg);
scores =0; times =0;
System.out.println("");
}
System.out.println("Highest average:" + highest_average);
}
}
以下是代码的示例运行:
Player 1
Enter your bowling score:
300
Enter your bowling score:
222
Enter your bowling score:
-1
Average= 261.00
Player 2
Enter your bowling score:
210
Enter your bowling score:
211
Enter your bowling score:
300
Enter your bowling score:
-1
Average= 240.00
Player 3
Enter your bowling score:
233
Enter your bowling score:
-1
Average= 233.00
Player 4
Enter your bowling score:
112
Enter your bowling score:
-1
Average= 112.00
Highest average:112.0 // this is not the highest score.
答案 0 :(得分:1)
您永远不会为每位玩家更新最高平均值,仅适用于最后一位玩家。这就是为什么你总是使用最后一个人的平均值。
只需在for循环中移动你的if语句,它应该可以正常工作。确保将print语句保留在循环外部,以便最后只打印一次最高平均值。
for (int i = 1; i <= players; i++) {
System.out.println("Player " + i);
do {
System.out.println("Enter your bowling score:");
G = keyboard.nextInt();
scores += G;
times++;
} while ((G != -1)); // -1 is what makes the loop end for the current player, a total of four players will get an average after -1 is inputted
scores += +1;
times = times - 1;
avg = (scores) / (times);
System.out.printf("Average= %.2f\n", avg);
scores = 0;
times = 0;
System.out.println("");
if (avg > highest_average) {
highest_average = avg;
}
}
System.out.println("Highest average:" + highest_average);
答案 1 :(得分:1)
if (avg > highest_average) {
highest_average= avg;
此代码应位于for循环中,否则最高平均值永远不会更新。