# 求一组数字的和sum,求平均数sum/n

## 代码

package com.kuang.scanner;

import java.util.Scanner;

public class Demon05 {
public static void main(String[] args) {
//我们可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输入执行结果;
Scanner scanner = new Scanner(System.in);   //创建一个扫描器的对象,用它接收键盘输入数据

//和
double sum = 0;
//计算输入了多少个数字
int m = 0;

//通过循环判断是否还有输入,并且里面对每一次进行求和和统计
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
m = m + 1; //m++
sum = sum + x;
System.out.println("你输入了第"+m+"个数据,当前结果sum="+sum);
}

System.out.println(m + "个数的和为" + sum);
System.out.println(m + "个数的平均值是" + (sum / m));

scanner.close();

}
}


## 运行结果

D:\environment\java\jdk1.8\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.3.2\lib\idea_rt.jar=51521:D:\IntelliJ IDEA 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\environment\java\jdk1.8\jre\lib\charsets.jar;D:\environment\java\jdk1.8\jre\lib\deploy.jar;D:\environment\java\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\environment\java\jdk1.8\jre\lib\ext\cldrdata.jar;D:\environment\java\jdk1.8\jre\lib\ext\dnsns.jar;D:\environment\java\jdk1.8\jre\lib\ext\jaccess.jar;D:\environment\java\jdk1.8\jre\lib\ext\jfxrt.jar;D:\environment\java\jdk1.8\jre\lib\ext\localedata.jar;D:\environment\java\jdk1.8\jre\lib\ext\nashorn.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunec.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\environment\java\jdk1.8\jre\lib\ext\zipfs.jar;D:\environment\java\jdk1.8\jre\lib\javaws.jar;D:\environment\java\jdk1.8\jre\lib\jce.jar;D:\environment\java\jdk1.8\jre\lib\jfr.jar;D:\environment\java\jdk1.8\jre\lib\jfxswt.jar;D:\environment\java\jdk1.8\jre\lib\jsse.jar;D:\environment\java\jdk1.8\jre\lib\management-agent.jar;D:\environment\java\jdk1.8\jre\lib\plugin.jar;D:\environment\java\jdk1.8\jre\lib\resources.jar;D:\environment\java\jdk1.8\jre\lib\rt.jar;E:\桌面\java学习\production\基础语法 com.kuang.scanner.Demon05
10

20

30

3个数的和为60.0
3个数的平均值是20.0

Process finished with exit code 0


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

hello_sunny123

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

02-29 1660
12-09 913
04-22 98
09-13 1740