我是一名学习如何编程的初学者。
public static void main()
{
int array[] = {1,-2,4,-4,9,-6,16,-8,25,-10};
System.out.print(stdev(array));
}
public static double stdev(int array[])
{
int stdev = 0;
int average = 0;
for(int i = 0; i<array.length;i++)
{
average = average+array[i];
}
average = average/array.length;
for(int i = 0; i <array.length;i++)
{
stdev = stdev +(array[i]- average)*(array[i]- average);
}
return Math.sqrt((double) stdev/(array.length));
}
}
在我的教科书中它说返回值是11.237,但我得到了10.672。请检查我的java代码。提前致谢
答案 0 :(得分:4)
平均值和stdev应该是双倍的,而不是整数。
average = average/array.length;
否则你最终会使用int division来返回一个截断的数字。
不同之处在于您的计算应使用&#34;更正的标准偏差&#34;根据{{3}}。平方根中的分子应该是数组的长度 - 1:
public static double stdev(int array[]) {
double sum = 0.0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
double average = sum / array.length;
double sumOfSquares = 0.0;
for (int i = 0; i < array.length; i++) {
sumOfSquares += (array[i] - average) * (array[i] - average);
}
// **** the issue is below -- you need to subtract 1 from array.length ******
return Math.sqrt(sumOfSquares / (array.length - 1));
}