我是递归概念的新手。我想写一个递归函数,它以 float 和整数作为参数,并以浮点值保持不变而整数值变化的方式递归调用它
我写了下面的代码:
#include <stdio.h>
float sum(float f, int k)
{
static float c;
c = f - k;
c = sum(f, k - 1);
return c;
}
int main()
{
float f, g = 10.00;
int i = 5;
f = sum(g, i);
printf("the sum of integer and float = %f", f);
}
当我编译它时它没有显示任何错误,但是当我运行该程序时它显示一个段错误。
我的问题如下:
- 代码有什么问题?
- 为什么显示段错误?
- 如何在具有多个参数的函数中使用递归?
请用一些有两个参数的递归函数的例子来解释一下。
最佳答案
代码是错误的,因为它永远不会结束(我假设它因 stackoverflow 错误而失败)。
对于递归,你需要两件事
- 基本案例
- 向基本情况移动的递归情况
看起来你只有第二个。我怀疑 sum 应该在 k
为零时返回。希望像这样的事情是有道理的:
float sum(float f, int k) {
if (k <= 0) {
// The base case
return f;
} else {
// The recursive case. This does one step of the work
// and moves towards the base case
return 1 + sum(f, k - 1);
}
}
关于c++ - c递归程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6224210/