簡體   English   中英

我想使用c中的遞歸函數查找給定數字的階乘。以下程序怎么了?

[英]i want to find the factorial of a given number using recursive function in c.what's wrong with the following program?

#include<stdio.h>

int fact(int i);
void main()
{
    int j;

    j=fact(4);

    printf("%d",j);
}

int fact(int i){
    int x=i;static int tot=1;

    if(x<1){
        tot=x*fact(x-1);
    }

    return tot;
}

請幫我這個代碼。 這段代碼在干什么?

您在事實函數中沒有基本條件。

您需要檢查:

 if(i == 1){
    return 1;
 }else{

   return i * fact(i - 1);

}
if(x<1)

您確定不是x > 1嗎?

另外,我會在您的tot聲明中擺脫static 這種對待tot類似於一個全局變量。 不用了 由於tot總是在讀取之前分配的,因此在這里看起來像無害,但總的來說它看起來像一個危險信號。

您在if語句中打印錯誤,應該是

if(x > 1) {
   tot=x*fact(x-1);
}

編輯:同時tot必須是非靜態的。

您不希望在tot聲明中使用static

暫無
暫無

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

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