[英]Calculating standard deviation in java
我是否在循环中计算我的标准偏差。 我知道计算标准偏差的公式,我只想知道如何获取用户输入进行计算。 我是编程新手,所以请解释一切。 我也不介意我试图写出标准偏差公式的抱歉尝试,它并不是为了更多地理解 SD 而工作。
import java.util.Scanner;
public class readFromKeyboard {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inStr = input.next();
int n;
int i;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double average=0;
int sum;
double deviation = 0;
while (!inStr.equals("EOL")) {
count++;
n = Integer.parseInt(inStr);
min = Math.min(min, n);
max = Math.max(max, n);
System.out.printf("%d ", n);
inStr = input.next();
average += n;
// really bad attempt here
deviation = math.pow(n / average,2) ++ / mean sqrt();
}
average = average/count;
System.out.println("\n The average of these numbers is " + average);
System.out.printf("The list has %d numbers\n", count);
System.out.printf("The minimum of the list is %d\n", min);
System.out.printf("The maximum of the list is %d\n", max);
input.close();
}
}
首先你的代码有几个问题:
您对average
使用非常令人困惑,因为您首先将其用作累加器,然后才将其除以元素数。 更好的风格是使用单独的累加器变量来计算总和,然后在 for 循环外计算平均值。
话虽如此,一旦计算出平均值,您就可以再次遍历您的值,并保留一个累加器变量,对于每个数字,该变量增加其与平均值之间的差值的平方,如下所示:
varianceSum += Math.pow(num - average, 2);
将所有数字相加后,您可以将varianceSum
总和除以count
以获得方差(可能检查以避免除以 0),并使用Math.sqrt()
找到标准偏差。
至于从用户那里获取输入,您需要为每个数字重复调用input.nextInt()
。 您可以让用户在开头输入输入的数量,然后在 for 循环中遍历它们,或者您可以使用 Scanner 的hasNext()
方法读取直到到达输入的末尾。
你应该调用input.next();
在循环内部重复获取用户输入。
为了记录,您可以使用in.nextInt()
而不是input.next();
,因为您在这里处理整数。 你的deviation
计算不清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.