C语言 C中数组的递归求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15801957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursive sum of an array in C
提问by MeesterMarcus
Hello I'm learning recursion in C and I am trying to find the sum of the elements.
你好,我正在学习 C 中的递归,我试图找到元素的总和。
This is my main:
这是我的主要内容:
int main()
{
int arr[] = {1,2,3,4,5};
int sum;
sum = arr_sum(arr,4);
printf("\nsum is:%d",sum);
return 0;
}
And my recursive function:
我的递归函数:
//n is the last index of the array
int arr_sum( int arr[], int n )
{ // must be recursive
int sum = 0;
//base case:
if (n < 0) {
return sum;
} else{
sum = sum + arr[n];
}
//make problem smaller
arr_sum(arr,n-1);
}
The output is:
输出是:
sum is :0
回答by imran
Try this for your recursive function:
试试这个为你的递归函数:
int arr_sum( int arr[], int n ) {
if (n < 0) {
//base case:
return 0;
} else{
return arr[n] + arr_sum(arr, n-1);
}
}
you need to add your n-th case to your n-1 case until you get to the base case.
您需要将第 n 个案例添加到您的 n-1 个案例中,直到达到基本案例。
回答by alex
You could add a third argument, which is the running total calculated so far (start it as 0).
您可以添加第三个参数,即到目前为止计算的运行总数(以 开头0)。
When you recursively call the function, pass the running total.
当您递归调用该函数时,传递运行总数。
int arr_sum( int arr[], int n, int sum )
{ // must be recursive
if (n < 0) {
return sum;
}
sum += arr[n];
return arr_sum(arr, --n, sum);
}
Alternatively, you change it to not require passing the sumvariable like so.
或者,您将其更改为不需要sum像这样传递变量。
int arr_sum( int arr[], int n )
{ // must be recursive
if (n < 0) {
return sum;
}
return arr[n] + arr_sum(arr, n - 1);
}
In this way, it is similar to finding a number in the Fibonacci sequence.
这样,它类似于在斐波那契数列中找到一个数字。
回答by lsk
Try this modified version of your program and work out on pen/paper the way it flows through. Hope it helps.
试试你的程序的这个修改版本,并在笔/纸上按照它流动的方式进行计算。希望能帮助到你。
#include <stdio.h>
//n is the last index of the array
int
arr_sum(int arr[], int n )
{
//base case:
if (n == 0) {
return arr[0];
}
return (arr[n] + arr_sum(arr,n-1));
}
int
main(void)
{
int arr[] = {1,2,3,4,5};
int sum;
sum = arr_sum(arr,4);
printf("\nsum is:%d\n",sum);
return 0;
}
回答by chintan
You are not returning any thing from else part.You also have return from that. like.
你没有从其他部分返回任何东西。你也有返回。喜欢。
return arr_sum(arr,n-1)+arr[n];
so this call the function again and again until n will be zero.
所以这一次又一次地调用该函数,直到 n 为零。
you got my point?
你明白我的意思吗?
回答by Maximin
The problem with your code is that everytime when your recursive function calls, it initializes the sum as 0.
您的代码的问题在于,每次当您的递归函数调用时,它都会将总和初始化为0。
Declare sumoutside the recursive method that will solve the problem.
sum在将解决问题的递归方法之外声明。

