c递归程序问题

Gol*_*olu 2 c c++ segmentation-fault

我是递归概念的新手.我想编写一个递归函数,它将float和integer作为参数,并以浮点值保持不变且整数值更改的方式递归调用它

我写下面的代码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

当我编译它时它没有显示错误,但是当我运行程序时它显示了一个分段错误.

我的问题如下:

  1. 代码有什么问题?
  2. 为什么它显示分段错误?
  3. 如何在具有多个参数的函数中使用递归?

请解释一下递归函数的一些例子,它有两个参数.

Jef*_*ter 6

代码是错误的,因为它永远不会结束(我认为它因堆栈溢出错误而失败).

对于递归,您需要两件事

  1. 一个基础案例
  2. 向基本案例移动的递归案例

看起来你只有第二个.我怀疑总和应该在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);
     }
 }
Run Code Online (Sandbox Code Playgroud)