创建一个程序,使用户能够输入一个整数N,然后读取N个双精度值,并打印它们的平均值(平均值)和样本标准偏差(它们与平均值的差值平方和的平方根,除以N - 1)。 到目前为止,我有这个代码
import java.util.Scanner;
public class AVGDevi
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double x;
double sum = 0;
double average = 0;
double dev = 0;
double var = 0;
double sqrx = 0;
int n = 0;
do
{
System.out.println("Enter an integer:");
x = input.nextInt();
if (x == -1)
{
break;
}
sum += x;
n++;
average = sum / n;
sqrx += Math.pow(x-average,2);
var = sqrx / (n-1);
dev = Math.sqrt(var);
} while (x<= 0);
System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
}
}
测试用例:
5
1
2
3
4
5
目前获得此输出
Enter an integer:
Average: 5.0
Deviation: NaN
输出应为
Enter an integer: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Average value is: 3.0
The standard deviation is: 1.58
我不是百分百肯定我做错了什么帮助会很棒:D!
答案 0 :(得分:1)
您在执行保护中使用x <= 0
,因此如果您输入正数,它将在第一次迭代后退出。此外,当您输入第一个数字时,您将获得var = sqrx / (n-1)
,但是对于n=1
,您将除以0.正如Hovercraft Full Of Eels建议的那样,我将这些数字添加到矢量中或ArrayList并在收到所有输入后进行计算。
答案 1 :(得分:1)
您只能使用while循环而不是do-while循环,如下所示:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double y=-1;
double sum = 0;
double average = 0;
double dev = 0;
double var = 0;
double sqrx = 0;
int n = 0;
System.out.println("Enter an integer:");
y = input.nextInt();
double z=y;
int i=0;
double x[] = new double[(int)z];
while(y-->0){
x[i] = input.nextDouble();
sum += x[i];
i++;
n++;
average = sum / n;
}
i=0;
while(z-->0){
sqrx += Math.pow(x[i]-average,2);
i++;
}
var = sqrx / (n-1);
dev = Math.sqrt(var);
System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
}