c - 使用递归求数组元素之和

标签 c

使用递归求数组中元素的总和

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, 
  system("pause") or input loop */
int max(int a[],int b,int x)
{
    if(a[x]!='\0'){
        return a[x]+max(a,b,x+1);
    }
}

int main()
{
    int a[30],b,x,c;
    scanf("%d",&b);
    for(x=0;x<b;x++){
        scanf("%d",&a[x]);
    }
    x=0;
    c=max(a,b,0);
    printf("%d",c);
}

输入:10 1 2 3 4 5 6 7 8 9 10
预期输出:55
实际输出:102

最佳答案

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, 
  system("pause") or input loop */
int max(int a[],int b,int x)
{
    if(x >= b)
        return 0;
    else {
        return a[x]+max(a,b,x+1);
    }
}

int main()
{
    int a[30],b,x,c;
    scanf("%d",&b);
    for(x=0;x<b;x++){
        scanf("%d",&a[x]);
    }
    x=0;
    c=max(a,b,0);
    printf("%d",c);
}


您刚刚错过了 max() 函数中的递归终止条件。

关于c - 使用递归求数组元素之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55369099/

相关文章:

c - 这段代码对搜索单向链表中的元素有效吗?

c - 如何停止 CSE 不要重复 CSE

c - 如何在 C 语言中声明一个可变大小的二维数组?

c - fwrite() 没有写入指定次数的数据

c++ - cmd内存使用情况

android - 在 android 中将 ffmpeg 作为库运行

c - Linux 设备驱动程序中的事件代码 (EVIOCG*)

c - armv5 上 c 中的指针分配错误

c - 初始化函数指针的全局数组

c - lwip ip_addr - 存储大小