我需要一個程序來計算一組數字的移動平均值(我使用4, 9,3.14,1.59,86.0,35.2,9.98,1.00,0.01,2.2,和3.76)。當我運行這個時,它會打印出 「17.859999999999996」九次。你們有沒有看到任何錯誤?如何在Java中創建移動平均數
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]);
}
}
}
當您使用調試程序執行程序時,或者在循環中插入'println'調用以查看中間值時,您看到了什麼? – Simon