[英]how to work function in c language anyone can explain please
在此代码中,为什么n次打印n次任何人都可以解释,请解释为什么n次打印n次
int count(int n){
print("%d" , n);
if(n>1){
count(n-1);
}
print("Integer value is %d\n" , n);
return n;
}
int main(){
count(3);
}
在给出的代码中,函数是递归的。 Count(n-1)反复调用该函数,直到条件if(n> 1)失败。 因此,如果要将5传递给count函数。 它打印5次。
对于count(n),您的代码将打印如下内容:
n,n-1,n-2....1 Integer value is 1
Integer value is 2
Integer value is 3
....
....
Integer value is n
现在让我们看一下原因,找到对count(3)的递归调用以进行说明:
count(3)-打印(3)
(3> 1)为真---- count(2)-print(2)
(2> 1)是true ---- count(1)-print(1)
(1> 1)是错误的exec prev func调用
print(整数值为2)返回2
打印(整数值为3)
返回3
在递归树中,查看代码在何处打印值。
Input: count(3)
Output:
321Integer value is 1
Integer value is 2
Integer value is 3
它打印出6次。 这是因为程序被告知。 让我们将函数调用插入到主代码中:
int count(3) // call with 3
{
print("%d" , 3); // prints 3
if(3>1)
{
count(3-1);
}
print("Integer value is %d\n" , n); // prints 3
return n;
}
再次插入呼叫:
int count(3) // call with 3
{
print("%d" , 3); // prints 3
if(3>1)
{
// count(3-1)
{
print("%d" , 2); // prints 2
if(2>1)
{
count(2-1);
}
print("Integer value is %d\n" , 2); // prints 2
return 2;
}
}
print("Integer value is %d\n" , 3); // prints 3
return 3;
}
再次:
int count(3) // call with 3
{
print("%d" , 3); // prints 3
if(3>1)
{
// count(3-1)
{
print("%d" , 2); // prints 2
if(2>1)
{
// count(2-1);
{
print("%d" , 1); // prints 1
if(1>1) // is false, no recursion any more
{
// count(1-1);
}
print("Integer value is %d\n" , 1); // prints 1
return 1;
}
}
print("Integer value is %d\n" , 2); // prints 2
return 2;
}
}
print("Integer value is %d\n" , 3); // prints 3
return 3;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.