计算数字的平均值(使用 while 循环;java)

Find average of numbers (with while loops; java)

我的代码在用户输入 -1 时停止(就像它应该的那样)但打印的平均值是错误的。

这是我的:

import static java.lang.System.*;
import java.util.Scanner;
import java.util.*;

class averages_1
{
    public static void main(String[] args)   
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the scores:");
        double score = 0;
        double num = 0;
        double sum = 0;

    while (score != -1)
    {
        score = scan.nextDouble();
        sum += score;
        num++;
    }
    System.out.println("The average is:" + (sum/num));
}

}

如果输入 50 然后输入 105 然后输入 -1,输出为

Enter the scores:

50

105

-1

The average is: 51.333333333333336

我只需要修正平均值。感谢您的帮助!

您只需将最后一个 -1 添加到您的总和中,仍然将其计为数字。如果你的输入是 -1,你必须 break; 你的循环。

您在平均值中包含了 -1。

避免它的一种方法是添加另一个条件:

while (score != -1)
{
    score = scan.nextDouble();
    if (score != -1) {
        sum += score;
        num++;
    }
}

但是,更优雅的解决方案是在循环之前读取第一个输入,并且只添加有效输入:

score = scan.nextDouble();
while (score != -1)
{
    sum += score;
    num++;
    score = scan.nextDouble();
}

一般来说,更改 while 循环条件中使用的变量应该是您在迭代中做的最后一件事。

你正在增加 num 即使 input==-1,这不是一个有效的输入,而是一个转义字符...

要么修改逻辑,要么只更正代码段:

System.out.println("The average is:" + (++sum/--num));

您可以在 while loop 的条件下读取输入, 这样,一旦您阅读 -1 就退出循环,它不会被添加到您的 sum 变量

while ((score=scan.nextDouble()) != -1)
{
    sum += score;
    num++;
}

如下更改代码

import static java.lang.System.*;
import java.util.Scanner;
import java.util.*;

class averages_1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the scores:");
        double score = 0;
        double num = 0;
        double sum = 0;
        while (score != -1) {
            sum += score;
            score = scan.nextDouble();
            num++;
        }
        num--;
        System.out.println("The average is:" + (sum/num));
    }
}

好的,那么就用这个

while (score != -1) {
        if (scope != -1){
           sum += score;
           score = scan.nextDouble();
           num++;
        }
    }

它不是很漂亮,但就像其他人告诉你的那样,不要将 -1 添加到分数中,因为它是你的转义字符。