2012-12-04 33 views
0

多的任務是創建一個使用遞歸,我成功地做了計算公式阿克曼的程序。所述任務的一部分表示:計數遞歸函數調用它是k的用C

「功能應該打印遞歸函數調用其是多個k的數目集合K = 100的n個 值;米< = 3,且k = 1; 000;。對於所有其他值,您的程序還應該打印所有函數調用的總數 。「

阿克曼功能應該是打印出來的函數調用和遞歸函數調用的次數,但我無法弄清楚如何做到這一點。任何幫助都會很棒。謝謝!

這是我到目前爲止有:

#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; 
} 
+1

使用全局變量,每次調用增加其價值。 –

回答

3
static int count = 0; 

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

使靜態變量,這將保持總數對功能的調用。

在這種情況下,你不必做count全球使其局部靜態到功能就足夠了,因爲靜態變量保留它的價值static具有文件範圍。

+0

我明白,但我不明白的是函數應該如何打印出遞歸函數調用的數量是k的倍數。 – user1876409

+0

據我瞭解,你可以在這裏應用一些邏輯的'k'多個像'如果(計數%K == 0)actual_count ++;'那麼你有'actual_count'變量,它會保留函數調用總數。因爲'count'現在跟蹤所有的函數調用,只需檢查它並增加另一個變量'actual_count',它也是'static'。 – Omkant

+0

@ user1876409:明白了,還是應該編輯我的答案呢? – Omkant

1

使用全局變量,每次調用增加它的價值:

int calls_count = 0; 

... 

int ackermann (int n, int m) 
{ 
    ++calls_count; 
...