2014-01-23 40 views
-6

您好我在C#中有問題,遞歸C#新手在遞歸函數失去

下面是代碼:

static int g(int a) 
{ 
    if (a > 0) 
    return -2 * g(a - 2) + 2; 
    else 
    return -2; 
} 

是什麼結果:

Console.WriteLine(g(5)); 

可能有人解釋當int沒有被聲明爲int a時,int g的值是什麼?

+1

「INT g」 爲什麼數據類型功能 「G」 的回報。 – Jim

+0

'GEE的結果是什麼,如果只有某種方法可以找出...... – tnw

回答

0

有人可以解釋一下,當不是 被聲明爲int a時,int g的值是多少?

我不明白這是什麼的問題是指,althought我要解釋一下什麼是函數的返回如果你通過5

首先讓聲明另一個整數,使其更容易:

static int g(int a) 
{ 
    if (a > 0){ 
     int result = g(a - 2); 
     return -2 * result + 2; 
    } 
    else 
    return -2; 
} 

然後:

Console.WriteLine(g(5)) //-2*(-10)+2 = 22 

if 5 > 0 
    result = g(3) //-2*(6)+2 = -10 
    return -2 * result + 2 

if 3 > 0 
    result = g(1) //result = -2*(-2)+2 = 6 
    return -2 * result + 2 

if 1 > 0 
    result = g(-1) //result = -2 
    return -2 * result + 2 

if -1 < 0 
    return -2 
-2

您似乎缺乏對遞歸的理解。讓我們簡化遞歸到一個比您的示例簡單得多的「經典」基本案例。讓我們做1的總和的輸入數量:

public int SumAll(int number) 
{ 
    // Base case 
    if (number == 1) 
    { 
     return 1; 
    } 

    // Recursive call 
    return number + SumAll(number - 1); 
} 

遞歸總是既包括調用內本身就是一種方法和停止循環中的「基本情況」或終止步驟。在上面的例子中,「基本情況」是等於1的數字來停止循環。

上面的例子將評估如下

return 5 + SumAll(4); 

而且SumAll(4)將作爲評估:

return 4 + SumAll(3); 

迄今爲止,我們的最終結果將是:

5 + 4 + Sum(3); 

等等...研究方法來理解爲什麼。

+3

這個答案與被問到的問題無關。 – Servy