gpt4 book ai didi

java - 如何在 Java 中创建移动平均线

转载 作者:行者123 更新时间:2023-12-01 18:42:51 27 4
gpt4 key购买 nike

我需要一个程序来计算一组数字的移动平均值(我使用了 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]);
}
}
}

最佳答案

由于这看起来像是一项作业,我会给你一个提示。

移动平均线有一个窗口。在这种情况下,窗口的宽度是averageLength。这是您平均获得的分数。

您需要在创建移动平均线的循环中以某种方式使用averageLength。现在你不需要了。

关于java - 如何在 Java 中创建移动平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19190360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com