2017-10-10 142 views
-3

我正在編寫一個程序,計算並顯示用戶輸入的每個投球手的平均保齡球分數。 我在計算3分數的平均數時遇到了麻煩,現在我認爲它是計算分數的總和。我如何使它所以它計算分數的平均Java如何計算3個保齡球分數的平均值

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")); 

     } 
+1

輸入和輸出你得到截至目前什麼平均? – notyou

+0

如果我爲每個分數輸入20,它表示平均值是46,不知道爲什麼 – user8723490

+1

提示:在代碼中大量地使用圓括號。 –

回答

4

Java的數學運算符遵守標準的數學優先級,所以它的

int average = score1 + score2 + (score3/3); 

但是, [R意向很可能

int average = (score1 + score2 + score3)/3; 

最後,您很可能希望進行這樣的計算中double(或float)運算,否則將被捨去

double average = (double)(score1 + score2 + score3)/3; 
+2

+1指出整數除法,雖然問題也有'平均'作爲'int',所以也應該可能是'雙' – SteveR

3

分工(/)操作符比加法運算符(+)的優先級高,所以你需要將之前爲封裝與支架的總和:

average = (score1 + score2 + score3)/3; 
// Here --^------------------------^