【问题标题】:Golf score program?高尔夫得分计划?
【发布时间】:2011-10-15 05:16:27
【问题描述】:

所以我正在尝试制作一个程序来平均计算您的高尔夫成绩。我编辑了一个标准平均计算器以使其工作:

import java.util.Scanner;
public class Test {
public static void main(String args[]){
    Scanner input = new Scanner(System.in);
    int total = 0;
    int score;
    int average;
    int counter = 0;

    while (counter >= 0){
    score = input.nextInt();
    total = total + score;
    counter++;
    }
    average= total/10;
    System.out.println("Your average score is "+ average);
}
}

但是当我输入分数时,我可以继续输入无限的分数,它永远不会平均它们。它只是一直期待另一个分数。我知道这与这条线有关:

while (counter >= 0){

但我不确定该怎么做才能正常工作。

【问题讨论】:

  • 您的while 循环只会在counter 不大于或等于0 时停止,并且您将counter 增加为counter++,因此绝不会出现这种情况。你确定这就是你想要的工作方式吗?或者你还希望你的循环如何结束?

标签: java average


【解决方案1】:

你永远找不到摆脱循环的方法:

while (counter >= 0){
    score = input.nextInt();
    total = total + score;
    counter++;
}

将循环 20 亿次 次(不,我没有夸大其词),因为您没有其他方法可以突破。

您可能想要的是将循环条件更改为:

int score = 0;

while (score >= 0){

当输入负分时,这将爆发。

此外,最后还有一个整数除法。你想做浮点数,所以把声明改成这样:

double average;

并将这一行更改为:

average = (double)total / 10.;

【讨论】:

    【解决方案2】:

    你需要一些方法来摆脱循环。例如输入-1:

    int score = input.nextInt();
    if (score < 0) { break; }
    total += score;
    

    您在计算平均值时似乎也有几个错误:

    • 不要总是除以 10 - 使用 counter 的值。
    • 使用浮点运算。如果您需要一个 int,您可能希望四舍五入到最近而不是截断。

    例如:

    float average = total / (float)counter;
    

    【讨论】:

      【解决方案3】:

      你必须指定计数器的值,默认值为0,所以while中的条件总是为真,所以你会陷入死循环。

      【讨论】:

        【解决方案4】:
        while (true) {
            score = input.nextInt();
            if (score == 0) {
                break;
            }
            total = total + score;
            counter++;
        }
        

        现在,当您输入不可能的分数 0 时,您的程序将意识到您已完成输入分数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-18
          • 1970-01-01
          • 1970-01-01
          • 2010-12-17
          • 2010-12-01
          • 2010-09-17
          相关资源
          最近更新 更多