C 用递归求数组元素之和
使用递归查找数组中元素的和C 用递归求数组元素之和,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
#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>
int sumation(int array[],int i) {
static int k = 0;
if(k == 10) {
return 0;
}
else {
++k;
return array[i] + sumation(array, i+1);
}
}
int main() {
int array[10], size, sum;
scanf("%d",&size);
for(int i = 0; i<size; i++) {
array[i] = i+1;
}
sum = sumation(array, 0);
printf("Sum:: %d ", sum);
return 0;
}
您可以通过给k-serrthrr指定size变量的值来更改k-serrthrr的值,或者在基本递归的if块中直接指定size常量的值
#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函数中的递归终止条件。您的问题是什么?我在代码中找不到错误。您能帮我找出数字0和\0是相同的,将停止您的递归。您希望检查X==b并返回0。真正的输入是什么?与您的问题无关,但需要注意的是,max对于该函数的名称选择非常糟糕。随着代码库变得越来越复杂,好的和描述性的名称将帮助您和其他人阅读和推理您的代码。