目前,我正在编写一个程序,其中需要一个变量 count
,每次调用该函数时该变量都会递增。就我而言,我有一个递归函数,并且想知道程序执行了多少次迭代。
我通过计算数字的阶乘来简化代码。
我的第一种方法不起作用,最终会出现警告消息:
#include <stdio.h>
int factorial(unsigned int i, int *count)
{
*count += 1;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, &count);
}
int main()
{
int i = 10;
int count = 0;
printf("%d Iterations, Factorial of %d is %d\n", count, i, factorial(i, &count));
return 0;
}
warning: passing argument 2 of ‘factorial’ from incompatible pointer type
我的第二种方法也不起作用,但也不会出现任何警告消息。
#include <stdio.h>
int factorial(unsigned int i, int count)
{
count += 1;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, count);
}
int main()
{
int i = 10;
int count = 0;
printf("%d Iterations, Factorial of %d is %d\n", count, i, factorial(i, count));
return 0;
}
如何让它运行?有任何想法吗?我使用 Ubuntu 和 gcc。
最佳答案
正如其他解决方案所建议的那样,不需要静态变量。下列说法正确的是:
int factorial(unsigned int i, int *count)
{
*count += 1;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, count);
}
int main(void)
{
int i = 10;
int count = 0;
printf("%d Iterations, Factorial of %d is %d\n", count, i, factorial(i, &count));
return 0;
}
注意一点:由于 printf
语句中参数求值的顺序无法保证,据我了解,调用 printf 时
可以是零(在调用阶乘之前传递),也可以是 10(在调用阶乘之后的值)。因此,main 最好写成:count
的值
int main(void)
{
int i = 10;
int count = 0;
int fact= factorial(i, &count);
printf("%d Iterations, Factorial of %d is %d\n", count, i, fact);
return 0;
}
6.5.2.2 Function calls: 10 The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
关于c - 如何在递归函数中实现运行变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503100/