【发布时间】:2018-05-17 09:00:24
【问题描述】:
我必须编写一个程序,读取一组浮点值(总共 10 个。它是固定的),然后计算并显示这些值的平均值、标准差、最小值、最大值, 第二大的值 它应该有一个循环。在循环中,提示用户输入一个数字(一个可以有小数部分的浮点数)并将该数字保存在一个变量中(双精度型)。我已经做到了,但是在实现循环以更容易地获取值时遇到了麻烦,因为我不知道如何在通过循环计算时保存它们。所以现在我的代码看起来非常丑陋和多余。
import java.util.Scanner;
public class Statistics {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
float average = 0;
float smallest = 0;
float largest = 0;
float scndLargest = 0;
float a, b, c, d, e, f, g, h, i, j = 0;
System.out.println("Enter values.");
a = s.nextFloat();
b = s.nextFloat();
c = s.nextFloat();
d = s.nextFloat();
e = s.nextFloat();
f = s.nextFloat();
g = s.nextFloat();
h = s.nextFloat();
i = s.nextFloat();
j = s.nextFloat();
average = (a + b + c + d + e + f + g + h + i + j) / 10;
float min1 = Math.min(a, b);
float min2 = Math.min(c, d);
float min3 = Math.min(e, f);
float min4 = Math.min(g, h);
float min5 = Math.min(i, j);
float min6 = Math.min(min1, min2);
float min7 = Math.min(min3, min4);
float min8 = Math.min(min7, min5);
smallest = Math.min(min6, min8);
System.out.println("The smallest value is: " + smallest);
float max1 = Math.max(a, b); //2
float max2 = Math.max(max1, c);
float max3 = Math.max(max2, d); //4
float max4 = Math.max(max3, e);
float max5 = Math.max(max4, f); //6
float max6 = Math.max(max5, g); //6
float max7 = Math.max(max6, h); //8
float max8 = Math.max(max7, i);
largest = Math.max(max8, j); //10
System.out.println("The largest value is: " + largest);
scndLargest = Math.min(largest, max8);
System.out.println("The second largest value is: " + scndLargest);
System.out.println("The average of all the values is: " + average);
double a1 = Math.pow(a - average, 2);
double b1 = Math.pow(a - average, 2);
double c1 = Math.pow(a - average, 2);
double d1 = Math.pow(a - average, 2);
double e1 = Math.pow(a - average, 2);
double f1 = Math.pow(a - average, 2);
double g1 = Math.pow(a - average, 2);
double h1 = Math.pow(a - average, 2);
double i1 = Math.pow(a - average, 2);
double j1 = Math.pow(a - average, 2);
double sum1 = Math.pow(a1 /10, 2);
double sum2 = Math.pow(b1 /10, 2);
double sum3 = Math.pow(c1 /10, 2);
double sum4 = Math.pow(d1 /10, 2);
double sum5 = Math.pow(e1 /10, 2);
double sum6 = Math.pow(f1 /10, 2);
double sum7 = Math.pow(g1 /10, 2);
double sum8 = Math.pow(h1 /10, 2);
double sum9 = Math.pow(i1 /10, 2);
double sum10 = Math.pow(j1 /10, 2);
double total = (sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7 + sum8 + sum9 + sum10);
double squaredVariance = (total) / 10;
double newTotal = Math.sqrt(squaredVariance);
System.out.printf("Standard deviation is: ");
System.out.printf("%.2f", newTotal);
}
}
【问题讨论】:
标签: java statistics standard-deviation