**5.45(统计:计算平均值和标准方差)在商务应用程序中经常需要计算数据的平均值和标准方差。平均值就是数字的简单平均。标准方差则是一个统计数字,给出了在一个数字集中各种数据距离平均值的聚集紧密度。例如,一个班级的学生的平均年龄是多少?年龄相差近吗?如果所有的学生都是同龄的,那么方差为0。编写一个程序,提示用户输入10个数字,然后运用下面的公式,显示这些数字的平均值及标准方差。

第五章第四十五题(统计:计算平均值和标准方差)(Statistics: compute mean and standard deviation)_方差

第五章第四十五题(统计:计算平均值和标准方差)(Statistics: compute mean and standard deviation)_java_02

下面是一个运行示例:

Enter 10 numbers: 1 2 3 4.5 5.6 6 7 8 9 10

The mean is 5.61

The standard deviation is 2.99794

 

**5.45(Statistics: compute mean and standard deviation)In business applications, you are often asked to compute the mean and standard deviation of data. The mean is simply the average of the numbers. The standard deviation is a statistic that tells you how tightly all the various data are clustered around the mean in a set of data. For example, what is the average age of the students in a class? How close are the ages? If all the students are the same age, the deviation is 0. Write a program that prompts the user to enter 10 numbers and displays the mean and standard deviations of these numbers using the following formula:

第五章第四十五题(统计:计算平均值和标准方差)(Statistics: compute mean and standard deviation)_方差

第五章第四十五题(统计:计算平均值和标准方差)(Statistics: compute mean and standard deviation)_java_02


Here is a sample run:


 


Enter 10 numbers: 1 2 3 4.5 5.6 6 7 8 9 10

The mean is 5.61

The standard deviation is 2.99794

 

下面是参考答案代码:

import java.util.*;


public class ComputeMeanAndStandardDeviationQuestion45 {
public static void main(String[] args) {
double sumOfSquares, sum, tempNumber, averageOfSum, deviation;

sum = sumOfSquares = 0;

Scanner inputScanner = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for(int i = 1;i <= 10;i++)
{
tempNumber = inputScanner.nextDouble();
sumOfSquares += tempNumber * tempNumber;
sum += tempNumber;
}
averageOfSum = sum / 10;
deviation = Math.sqrt((sumOfSquares - (sum * sum / 10)) / 9);

System.out.printf("The mean is %.2f\n", averageOfSum);
System.out.printf("The standard deviation is %.5f", deviation);

inputScanner.close();
}
}

运行效果:

第五章第四十五题(统计:计算平均值和标准方差)(Statistics: compute mean and standard deviation)_方差_05

 

注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等