2017-10-10 36 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」であるため、おそらくは「double」である必要があります – SteveR

3

部門(/)演算子は加算演算子(+)よりも高い優先順位を持っているので、あなたが割る前に括弧付きの和を同封する必要があります。

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