为什么这个程序输出0000 [英] Why this output 0000 for this program

查看:81
本文介绍了为什么这个程序输出0000的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[

#include <stdio.h>
#include <stdlib.h>

int main()
{
    static int i=5;
    if(--i)
    {
    main();
    printf("%d\n",i);
    }
    return 0;
}



]


]

推荐答案

你所拥有的是头部递归。请参阅 head& amp;尾递归 [ ^ ]。只要静态变量 i 不为零,就会发生递归(4次)。在展开递归时(在每个递归调用的尾部),将打印静态变量的当前值。如果它是本地变量而不是静态变量,则结果不同 - >堆栈溢出,因为递归的停止条件从未得到满足。

干杯

Andi
What you have is head recursion. See The difference between head & tail recursion[^]. As long as the static variable i is not zero, the recursion takes place (4 times). While unwinding the recursion (in the tail of each recursive call), the current value of the static variable is printed. If it was a local variable instead of a static variable, the result was different --> a stack overflow since the stop condition for the recursion was never met.
Cheers
Andi


这是因为,当它到来时对于printf,输出变量i的值变为零。

您可以在main之前放置printf。

更好地编写这样的递归:



This happens because, when it comes to "printf", the value of a output variable "i" became zero.
You can put "printf" before "main".
More better to write recursion like this:

void recuot(int n)
{
	if (n > 1)
		recuot(n-1);
	printf("%d\n",n);;
}
int main()
{
	recuot(5);
	return 0;
}


这篇关于为什么这个程序输出0000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆