#include <stdio.h>
long long factorial(int n) {
if (n == 0) // 基礎情況
return 1;
else // 遞迴步驟
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter a positive integer greater than 1: ");
scanf("%d", &n);
if (n < 0) {
printf("Please enter a positive integer.\n");
} else {
printf("%d! = %lld\n", n, factorial(n));
}
return 0;
}
這個程序首先定義了一個名為factorial的遞迴函式,用於計算一個整數n的階乘。在主函式main中,程序將從用戶那裡讀取一個正整數,然後調用factorial函式來計算並打印這個數字的階乘。這個實現假定了輸入的數字大於或等於0,因為負數的階乘是未定義的。