0

任务是创建一个使用递归计算阿克曼方程的程序,我成功地做到了。部分作业说:

“函数应该打印递归函数调用的数量,它是 k 的倍数。对于 n 的值设置 k = 100;m <= 3,并且对于所有其他值设置 k = 1;000;000。您的程序还应该打印进行的函数调用总数。”

ackermann函数应该打印出函数调用和递归函数调用的数量,但我不知道该怎么做。任何帮助都会很棒。谢谢!

这是我到目前为止所拥有的:

#include <stdio.h>

//function to compute the end result ackermann equation
int ackermann (int n, int m)
{
    int result = 0;

    if (n == 0)
    {
        result = m + 1;

    } else if (m == 0)
    {
        result = ackermann(n - 1, 1);

    } else
    {
        result = ackermann(n - 1, ackermann(n, m - 1));
    }

    return result;
}

//main function
int main(int argc, const char * argv[])
{
    char ans = 'y';
    int m, n, result;

    printf("\n\n------Ackermann Function------");

    while (ans == 'Y' || ans == 'y') {
        printf("\nPlease enter n: ");
        scanf("%d", &n);

        printf("\nPlease enter m: ");
        scanf("%d", &m);

        result = ackermann(n, m);

        printf("\nResult: %d", result);

        printf("\n\nDo you want to go again? ");
        scanf(" %c", &ans);
    }

    return 0;
}
4

2 回答 2

4
static int count = 0;

int func() 
{
  count ++
  // do your work
  // recursive call
}

制作静态变量,它将保留对函数的调用总数。

在这种情况下,您不必将其count设为全局,使其成为本地静态函数就足够了,因为静态变量保留了它的值,因为它static具有文件范围。

于 2012-12-04T16:59:19.860 回答
1

使用全局变量,在每次调用时递增其值:

int calls_count = 0;

...

int ackermann (int n, int m)
{
    ++calls_count;
...
于 2012-12-04T16:57:34.040 回答