考虑以下递归 C 函数。
void get (int n) {
if (n<1) return;
get (n-1) ;
get (n-3) ;
printf ("%d", n) ;
}
如果在 main()
中调用 get(6)
函数,那么之前会调用 get()
函数多少次返回主0
?
最佳答案
要计算出您的函数被调用了多少次,请在每次进入该函数时增加一个静态计数器,并在调用后打印出该值。例如:
int counter;
void get (int n) {
++counter; /* increment counter before first return */
if (n<1) return;
get (n-1) ;
get (n-3) ;
printf ("%d", n) ;
}
int main()
{
counter = 0; /* reset counter before each use */
get(6);
printf("get() was called %d times\n", counter);
}
关于c - 如何找到递归函数调用自身的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28470909/