我正在嘗試使用遞回函式。但是我失敗了,這是分段錯誤。
#include <stdio.h>
int factorial( int x );
int main(){
factorial(4);
return 0;
}
int factorial( int x ){
return x* factorial(x-1);
}
我在 Python 和 C 編程中看到了相同的代碼并沒有取得同樣的成功。我想知道為什么以及如何解決這個問題
uj5u.com熱心網友回復:
問題是你沒有告訴階乘函式什么時候結束。試試吧
long factorial(int x) {
if (n == 0)
return 1;
else
return(x * factorial(x-1));
}
像這樣,當它到達數字 0 時會停止并從 x 回傳階乘。這是有效的,因為數字 n 的階乘由以下公式給出:n * n-1 * n-2 * ... * 1。但是您正在嘗試像 n * n-1 * ... * -inf 一樣計算它
uj5u.com熱心網友回復:
這是因為階乘函式中沒有定義基本條件來處理零值。
int factorial( int x ){
if (x == 0)
return 1;
else
return x* factorial(x-1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532415.html
下一篇:有沒有辦法將函式存盤在向量中?
