为了账号安全,请及时绑定邮箱和手机立即绑定

Java等分数

Java等分数

富国沪深 2021-06-22 17:12:00
我正在练习一个问题:键入多个数字并在键入 0 时停止。打印出您键入的数字的最大值、最小值和平均值。以下是我的代码,我被困在平均值的计算中。例如:当我输入:2 5 7 -1 0 结果是:Type some numbers, and type 0 to end the calculattion: 2 5 7 -1 0The numbers you type are: 2 5 7 -1 Sum is: 13There are 4 numbersThe Max number is : 7The minimum number is : -1Average 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);}
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

这是整数除法的问题。sum/count计算为 int 因为sum并且count是类型int。您可以通过隐式强制转换来解决这个问题 。


尝试 :-


double avg = sum*1.0/count;   // implicit casting.

输出 :-


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.25


查看完整回答
反对 回复 2021-06-30
  • 1 回答
  • 0 关注
  • 120 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信