Java等分数

我正在练习一个问题:键入多个数字并在键入 0 时停止。打印出您键入的数字的最大值、最小值和平均值。


以下是我的代码,我被困在平均值的计算中。例如:当我输入:2 5 7 -1 0 结果是:


Type some numbers, and type 0 to end the calculattion: 

2 5 7 -1 0

The numbers you type are: 

2 5 7 -1 

Sum is: 13

There are 4 numbers

The Max number is : 7

The minimum number is : -1

Average is : 3.0

但是,平均值应为 3.25。我已经将变量 avg 设为 double 类型,为什么我的输出仍然是 3.0 而不是 3.25?


谢谢!!


public class Max_Min_Avg {



public static void main(String[] args) {

    System.out.println("Type some numbers, and type 0 to end the calculattion: ");

    Scanner scanner = new Scanner(System.in);

    int numbs = scanner.nextInt();

    int count =0;

    int sum =0;

    int max = 0;

    int min=0;

    System.out.println("The numbers you type are: ");

    while(numbs!=0) {

        System.out.print(numbs + " ");

        sum += numbs;

        count ++;

        numbs = scanner.nextInt();

        if(numbs>max) {

            max = numbs;

        }

        if(numbs<min) {

            min = numbs;

        }

    }

    while(numbs ==0) {

        break;


    }


    System.out.println();

    double avg = (sum/count);

    System.out.println("Sum is: "+ sum);

    System.out.println("There are "+ count + " numbers");

    System.out.println("The Max number is : " + max );

    System.out.println("The minimum number is : " + min);

    System.out.println("Average is : " + avg);


}


富国沪深
浏览 121回答 1
1回答

慕田峪7331174

这是整数除法的问题。sum/count计算为 int 因为sum并且count是类型int。您可以通过隐式强制转换来解决这个问题 。尝试 :-double avg = sum*1.0/count;&nbsp; &nbsp;// implicit casting.输出 :-Type some numbers, and type 0 to end the calculattion:&nbsp;2 5 7 -1 0The numbers you type are:&nbsp;2 5 7 -1&nbsp;Sum is: 13There are 4 numbersThe Max number is : 7The minimum number is : -1Average is : 3.25
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java