简体   繁体   English

递归函数从int数组三乘三元素计算平均值

[英]Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result. 用三个元素计算平均值三,然后用平均值结果替换那些元素。

Example array [1,2,7,-2,5,0, 2,8] After transformation [3,3,3,1,1,1,5,5] 示例数组[1,2,7,-2,5,0, 2,8]转换后[3,3,3,1,1,1,5,5]

Something is wrong, I can't get it to work. 出了点问题,我无法正常工作。

#include <stdio.h>

int main ( )    {
    int n, c[n];
    int *avg;
    int pom=0;

    printf("Enter lenght of array\n");

    scanf("%d",&n);

    printf("Enter elements");

    for(i = 0;i < n; i++)
        scanf("%d",c[i]);

    avg=Average(c , n, pom);

    for(i = 0; i < n; i++)
        printf("Avg elements= %d",*(avg+i))
    return 0;
}

int Average(int arr[], int size, int z)
{
    int k, l, m, Asum;

    if (size < 0) {
        return arr;
    } else {
        k=arr[z];
        l=arr[z+1];
        m=arr[z+2];

        Asum=(k + l + m)/3;

        arr[z]=Asum;
        arr[z+1]=Asum;
        arr[z+2]=Asum;
    }

    return Average(arr,size--,z++);
}

int n, c[n]; is a problem. 是个问题。 n is uninitialized so the size of the array is who-knows-what? n未初始化,因此数组的大小是谁知道的? This is undefined behavior. 这是未定义的行为。

Instead 代替

int main(void) {
  int n;
  int *avg;
  int pom=0;

  printf("Enter length of array\n");
  if (scanf("%d",&n) != 1) return -1;
  int c[n];

  for(i = 0;i < n; i++)
    // scanf("%d",c[i]);
    scanf("%d",&c[i]);  // pass the address of an `int`

Likely other issues too. 可能还有其他问题。

Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? 首先尝试简单输入,想象一下仅输入1个数字会发生什么,Average函数会做什么? Don't run the code but try to execute it in your head or with pencil and paper. 不要运行代码,而是尝试用脑袋或铅笔和纸执行它。 If you think the program only has to work with three or more numbers, try three. 如果您认为程序只需要处理三个或更多数字,请尝试三个。

A serious program would explicitly reject invalid input. 认真的程序会明确拒绝无效输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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