簡體   English   中英

Java如何計算3個保齡球得分的平均值

[英]Java How to calculate the average of 3 bowling scores

我正在編寫一個程序來計算和顯示用戶輸入的每個保齡球手的平均保齡球得分。 我在計算 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"));

      }

Java 的數學運算符遵循標准的數學優先級,所以它是

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

但是,您的意圖很可能

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

最后,您很可能想在double (或float )算術中進行此計算,否則將四舍五入

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

除法 ( / ) 運算符的優先級高於加法運算符 ( + ),因此您需要在除法之前將總和用括號括起來:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM