简体   繁体   中英

How can I calculate the moving average of the array?

In Question, When an array X of size n and a degree k are input, Write a program that calculates the k-th moving average of array X . The kth-order moving average of the array X consisting of primitive data values is the average of the last k elements up to the i-th point of X .

That is, A [i] = (X [ik + 1] + X [ik + 2] + ... + X [i]) / k .

If the number of the preceding element (including itself) is smaller than k, Calculate as an average.

For example, if array X is as follows and k is 3 , X = 1 3 2 10 6 8

The third moving average is as follows.

A = 1 2 2 5 6 8 A [1] = (1 + 3) / 2, A [2] = (1 + 3 + 2) / 3

However, the program must have the execution time of O (n), not O (nk). Round off the decimal point in the average calculation and obtain it as an integer. For exact rounding, do not use% .f, but round it using the int property.

int main()
{
  int i, n1, k;
  int *array1;
  scanf("%d", &n1);
  array1 = (int *)malloc(sizeof(int)*n1);
  scanf("%d", &k);
  for (i = 0; i < n1; i++)
  {
    scanf("%d", &array1[i]);
  }

double tmp = 0;
for (int i = 0; i < n1; i++)
{
    tmp += array1[i];

    if (i >= k)     
    {
        tmp -= array1[i - k];
    }
    if (i >= k - 1) 
    {
        double average = tmp / k;
        printf("%2lld ", llrint(average));
    }

    return 0;
}

The program does not work because the problem is not understood. I would like to know how to solve it.

add) Thank you for answer but the output required by the problem is as follows.

Input : 9 4 (n = 9, k = 3)
         2 7 4 5 6 8 2 8 13
 Output : 2 5 4 5 6 6 5 6 8

After Modifying your code

int main()
 {
    int i, n1, k;
    int *array1, *array2;
    scanf("%d", &n1);
    array1 = (int *)malloc(sizeof(int)*n1);
    scanf("%d", &k);
    for (i = 0; i < n1; i++)
    {
        scanf("%d", &array1[i]);
    }

    double tmp = 0;
    for (int i = 0; i < n1; i++)
    {
        tmp += array1[i];
        // now tmp contains exactly k + 1 elements sum
        // so subtract elements outside of k sized window(leftmost element)
        if(i >= k) {
            tmp -= array1[i - k];
        }
        if(i >= k - 1) {
            double average = tmp / k;
            printf("%lf\n", average);
        }
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM