繁体   English   中英

请,您能帮我这个递归函数吗?

[英]Please, can you help me with this recursive function?

#include <stdio.h> 
int  fun (int x)
 {
      if (x<1)
        return(1);
      else
        printf("%d %d \n", x, fun(x-1));
 }
int main()
 { int x,y;
   x = 5;
   y = fun(x);
   printf("\n x = %d f(x) = %d \n", x, y);
   return 0;
  }

该程序包含一个计算一些数字的递归函数。 输出中有些东西我听不懂。 以下链接提供了输出的屏幕截图:

https://onedrive.live.com/redir?resid=BE4862D617298D2C!886&authkey=!AA03bF8dQ5W4S9Y&v=3&ithint=photo%2cpng

为什么显示右栏(红色圆圈)? 我认为本专栏将全部代替。

因为当x> = 1时, fun函数没有返回值。

而5是printf("%d %d \\n", x, fun(x-1));的返回值printf("%d %d \\n", x, fun(x-1)); 因为它已输出5个字符。

如果x>=1 ,则不返回任何内容,当执行到达函数末尾时会导致未定义的行为。 这意味着该值可以是任何值,您偶然得到5。

6.9.1。 第12页:

如果到达终止函数的},并且调用者使用了函数调用的值,则该行为未定义。

在您的示例中使用了返回值。

int fun(int x)
{
    if (x<1)
        return(1);
    else
        printf("%d %d \n", x, fun(x-1));

    return x ;//just return something
}

您可能想返回与您的功能有关的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM