【问题标题】:Java How to calculate the average of 3 bowling scoresJava如何计算3个保龄球得分的平均值
【发布时间】:2017-10-10 20:52:22
【问题描述】:

我正在编写一个程序来计算并显示用户输入的每个投球手的平均保龄球得分。 我在计算三个分数的平均值时遇到了麻烦,现在我认为它正在计算分数的总和。我如何使它计算分数的平均值

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

      }

【问题讨论】:

  • 目前平均而言,您获得了哪些输入和输出?
  • 如果我为每个分数输入 20,它表示平均为 46,不知道为什么
  • 提示:在你的代码上多加括号。

标签: java while-loop average


【解决方案1】:

Java 的数学运算符遵循标准的数学优先级,所以是

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

但是,你的意图很可能

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

最后你很可能希望在double(或float)算术中进行此计算,否则将被舍入

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

【讨论】:

  • +1 用于指出整数除法,虽然问题也有 averageint,所以也应该是 double
【解决方案2】:

除法 (/) 运算符的优先级高于加法运算符 (+),因此在除法之前需要用括号将总和括起来:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2017-01-26
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多