簡體   English   中英

C遞歸程序無法使用GCC進行編譯

[英]C Recursion program won't compile w/ GCC

#include <stdio.h>

int main (void)

{
int n, x;

int factorial (int n)
{
if (x<=0)
{
 printf("x equals: ");
return 1;
}
else
{
return n * factorial (n-1); 
}
f(x)=f(x-1)+2; //says error is here
}
return 0;
}

我已經嘗試了一些方法,但無法正常工作。 我可能會很勞累,過去的事最小,但幫助將不勝感激! 謝謝 :)

您不能在main()或任何其他函數中聲明函數定義...函數定義必須是獨立的,並且不能在其中包含嵌入式函數定義。

另外,由於f()不是已定義的函數,因此我不確定在被標記為錯誤的那一行上的操作,因此無法調用它。 此外,它將需要返回某種類型的l值,例如指向函數內部聲明的靜態變量的指針,或通過引用傳遞給函數的指針,即使這樣,語法仍然不正確,因為將需要取消引用...所以基本上您不能做那一行上的工作。

要獲得可編譯的內容,請嘗試

#include <stdio.h>

int factorial (int n)
{
    if (n <= 0)
    {
        return 1;
    }
    else
    {
        return n * factorial (n-1); 
    }
}

int main (void)
{
    int x;

    x = factorial(5);
    printf("Factorial of 5 is equal to %d", x);

    return 0;
}

使用縮進查看范圍的可能問題:

 #include <stdio.h>

int main (void)
{
    int n, x;

int factorial (int n)
{
    if (x<=0)
    {
        printf("x equals: ");
        return 1;
    }
    else
    {
        return n * factorial (n-1); 
    }
    f(x)=f(x-1)+2; //says error is here
}
return 0;

}

據我所記得,C沒有閉包。

一個函數不能在另一個函數中定義。 但是gcc允許它作為擴展。 您已經定義了一個名為factorial的函數,但是正嘗試使用尚未在任何地方聲明的f

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM