使用递归求数组中元素的总和
#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/