我需要一个程序来计算一组数字的移动平均值(我使用了 4、9、3.14、1.59、86.0、35.2、9.98、1.00、0.01、2.2 和 3.76)。当我运行它时,它会打印出九次“17.859999999999996”。各位看官有没有看错?
import java.util.*;
public class MovingAverage
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
// Read in the length of the moving average and the number
// of data points
int averageLength = scan.nextInt();
int numDataPoints = scan.nextInt();
// Create an array to hold the data points, and another to
// hold the moving average
double data[] = new double[numDataPoints];
double movingAverage[] = new double[numDataPoints];
// Read in all of the data points using a for loop
for(int i = 0; i< numDataPoints; i++)
{
data[i]=scan.nextDouble();
}
// Create the moving average
for (int i=0; i<numDataPoints; i++)
{
// Calculate the moving average for index i and put
// it in movingAverage[i]. (Hint: you need a for
// loop to do this. Make sure not to use i as your
// loop variable. Also, make sure to handle the
// case where i is not large enough (when i<averageLength-1).
double sum= 0.0;
for(int j=0; j<numDataPoints; j++)
{
sum=sum+data[j];
movingAverage[i]=sum/j;
}
}
// Print the moving average, one value per line
for (int i=0; i<numDataPoints; i++)
{
System.out.println(movingAverage[i]);
}
}
}