c - 如何在递归函数中实现运行变量

标签 c recursion printf function-call

目前,我正在编写一个程序,其中需要一个变量 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 时 count 的值 可以是零(在调用阶乘之前传递),也可以是 10(在调用阶乘之后的值)。因此,main 最好写成:

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/

相关文章:

c - 将带有 for 循环的递归函数转变为纯递归

python - 序列的递归求和返回错误结果

c++ - 包含自身实例化的模板,C++ 中的递归

调用 sprintf 函数

c - 在文件的不同行附加一个字符串?

c - C 中的 Accept() - 套接字编程

c - realloc 二维结构体数组

c - 为什么 Isdigit 函数不能正常工作?

根据变量的值更改 printf() 中的文本

c++ - 将数组的某些元素转移/分离到其他数组