Java如何计算3个保龄球得分的平均值
我正在编写一个程序,计算并显示用户输入的每个保龄球手的平均保龄球分数。 我在计算3个分数的平均值时遇到了麻烦,现在我想这是在计算总分数。我如何使它计算平均分数Java如何计算3个保龄球得分的平均值,java,while-loop,average,Java,While Loop,Average,我正在编写一个程序,计算并显示用户输入的每个保龄球手的平均保龄球分数。 我在计算3个分数的平均值时遇到了麻烦,现在我想这是在计算总分数。我如何使它计算平均分数 public static void main (String [] args) { //local constants //local variables String bowler = ""; int total = 0; int average = 0; int score1 = 0;
public static void main (String [] args)
{
//local constants
//local variables
String bowler = "";
int total = 0;
int average = 0;
int score1 = 0;
int score2 = 0;
int score3 = 0;
/******************** Start main method *****************/
//Enter in the name of the first bowler
System.out.print(setLeft(40," Input First Bowler or stop to Quit: "));
bowler = Keyboard.readString();
//Enter While loop if input isn't q
while(!bowler.equals("stop"))
{
System.out.print(setLeft(40," 1st Bowling Score:"));
score1 = Keyboard.readInt();
System.out.print(setLeft(40," 2nd Bowling Score:"));
score2 = Keyboard.readInt();
System.out.print(setLeft(40," 3rd Bowling Score:"));
score3 = Keyboard.readInt();
if(score1 >= 0 && score1 <= 300 && score2 >= 0 && score2 <= 300 && score3 >= 0 && score3 <= 300)
{
total += score1;
total += score2;
total += score3;
System.out.println(setLeft(41,"Total: ")+ total);
average = score1 + score2 + score3 / 3;
System.out.println(setLeft(41,"Average: ") + average);
}
else
{
System.out.println(setLeft(40,"Error"));
}
除法/运算符的优先级高于加法运算符+,因此需要在除法前用括号括起和:
average = (score1 + score2 + score3) / 3;
// Here --^------------------------^
Java的数学运算符遵循标准的数学优先级,因此
int average = score1 + score2 + (score3 / 3);
然而,你的意图是可能的
int average = (score1 + score2 + score3) / 3;
最后,您很可能希望使用double或float算法进行此计算,否则将向下舍入
double average = (double)(score1 + score2 + score3) / 3;
到目前为止,平均分的输入和输出是什么?如果我为每个分数输入20,它表示平均分是46,不确定为什么p:在代码上随意地加上括号。+1用于指出整数除法,尽管这个问题的平均值也为int,因此也可能是双精度的