【问题标题】:How to calculate the average of a sequence of integer numbers read from the console?如何计算从控制台读取的整数序列的平均值?
【发布时间】:2018-10-12 18:24:54
【问题描述】:

为了计算用户输入数字的平均值,我的代码中缺少什么?

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n;
    float average;
    do {
        System.out.print("Enter a number: ");
        n = scanner.nextInt();
        System.out.println("Your number is " + n);
    } while (n != 0);

    if (n == 0) {
        System.out.println("The average is : " + n);
    }

    scanner.close();
}

}

当用户输入“0”时,程序应该计算用户输入数字的平均值,这就是我写“while (n != 0)”的原因。

【问题讨论】:

    标签: java eclipse average


    【解决方案1】:

    你应该这样做: 请注意,由于您还有一个数字(零),因此在计算平均值时必须通过删除它来考虑它,因为您要求 0 来完成程序。

    公共类Teste {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n;
        double average = 0;
        int qtdNums = 0;
        do {
            System.out.print("Enter a number: ");
            n = scanner.nextInt();
            System.out.println("Your number is " + n);
    
            average = average + n;
            qtdNums++;
        } while (n != 0);
    
        if (n == 0) {
            System.out.println("The average is : " + average / (qtdNums - 1));
        }
    
        scanner.close();
    }
    }
    

    【讨论】:

    • 感谢您的帮助,它工作正常!但我不太明白为什么 qtdNums - 1?那是 0 - 1 吗?以及带有 qtdNums++ 的部分。你能这么快解释我吗:)?
    • 您正在考虑所有数字的平均值。假设用户通知 5 个数字加上 0 停止,那么您总共有 6 个,但您只需要 5 个来计算平均值。这就是为什么你必须删除 1
    • @Larry 查看我的派生答案(我给了 jhenrique 学分)
    【解决方案2】:

    你实际上并没有使用你正在阅读的数字。一个好的编辑会在你运行它之前告诉你。我会考虑获得Eclipse IDE。你会想要做类似于jhenrique 建议的事情。我会说最好将数字添加为整数,然后再进行转换,这样您就不会失去浮点加法的准确性,这在某些情况下可能会给您带来很多麻烦(但在这里您可能很好)。这是我建议的代码,根据 jhenrique 的回答修改:

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n;
        int sum = 0;
        int count = 0;
        do {
            System.out.print("Enter a number: ");
            n = scanner.nextInt();
            System.out.println("Your number is " + n);
    
            sum += n;
            count++;
        } while (n != 0);
    
        System.out.println("The average is : " + ((double) sum) / (count - 1));
    
        scanner.close();
    }
    

    double 类似于float,但更准确。在循环中,我将每个读取数添加到sum,然后除以最后读取的内容数以获得平均值。

    【讨论】:

    • 是的,我明白了,您的两个代码都可以正常工作,但您的代码更容易理解!无论如何,我感谢您的帮助和良好的解释!
    猜你喜欢
    • 1970-01-01
    • 2020-07-07
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2011-03-08
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多