Java中数字的总和和平均值

时间:2016-10-27 00:25:16

标签: java integer sum average

以下是代码,但未针对所有异常进行优化。例如,如果用户从头开始输入0,它将给出除零错误,并且我也不知道为什么数字的总和有效。

基本上,我使num = 1所以它与0不同,所以while循环可以开始,但最后,我做了sum = sum - 1;但它给出了错误的数字。

请帮帮我。

import java.util.Scanner;
class Main {
    public static void main (String[] args) {
        int count = 0;
        int num = 1;
        double average = 0.0;
        int soma = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Type a integer. 0 to exit.");

        while (num != 0) {
            num = scanner.nextInt();
            sum = sum + num;
            count++;
        }
        if (num == 0) {
            average = sum / (count -1); 
            System.out.println("The sum of the numbers is:  "+ soma);
            System.out.println("The average of the numbers is: "+ media);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

改变做什么时间:

do {
    num = scanner.nextInt();
    sum = sum + num;
    count++;
}while (num != 0);

更改FROM:

average = sum / (count -1); 
System.out.println("The sum of the numbers is:  "+ soma);
    System.out.println("The average of the numbers is: "+ media);

TO:

 average = sum / (count); 
 System.out.println("The sum of the numbers is:  "+ sum);
    System.out.println("The average of the numbers is: "+ average);

它应该有用