分別使用 for 與 while 迴圈計算 5 的階乘 (5! = 120)。
#include <stdio.h>
int main() {
int result = 1;
for (int i = 1; i <= 5; i++) // 1*2*3*4*5
result *= i;
printf("%d\n", result); // 120
return 0;
}
#include <stdio.h>
int main() {
int result = 1;
int i = 1;
while (i <= 5) {
result *= i;
i++;
}
printf("%d\n", result); // 120
return 0;
}
unsigned long long factorial(int n) {
if (n < 0) return 0; // 錯誤處理
unsigned long long res = 1;
for (int i = 2; i <= n; i++) res *= i;
return res;
}
// 20! = 2,432,902,008,176,640,000 < 2^64-1,64位無符號可容納 20!
// 21! 溢位,需大數庫
for 適合「已知次數」迴圈,初始化/條件/迭代集中管理。while 適合「未知次數/條件複雜」迴圈。int (13! 溢位)、long long (20! 溢位),實際專案需大數或浮點近似 (Stirling 公式)。