初學 C++ 時常遇到階乘與數學常數 e 的計算練習。本文整理兩個經典範例,分別示範如何用 while 迴圈計算階乘,以及如何利用級數展開近似求得 e 值。
輸入一個非負整數 x,輸出 x!。程式碼如下:
unsigned int x;
unsigned int jc = 1;
cout << "請輸入一個非負整數:" << endl;
cin >> x;
while (x) {
jc *= x;
x--;
}
cout << "x!=" << jc << endl;
說明:利用 while(x) 在 x 變為 0 時結束迴圈,每次將 jc 乘以當前 x 並遞減 x,最終得到階乘結果。
輸入求和項數 n,依公式 e = 1/0! + 1/1! + 1/2! + ... 累加。程式碼如下:
int n = 1;
int jc = 1;
float e = 0.0;
int i = 0;
cout << "請輸入求和項數:" << endl;
cin >> n;
while (i < n) {
if (i == 0) jc = 1;
else jc *= i;
i++;
e += 1.0 / jc;
}
cout << "數學常量e=" << e << endl;
說明:迴圈中動態更新階乘 jc,避免重複計算;1.0 / jc 強制浮點除法,累加至 e。

兩個範例均展示了 while 迴圈在數學計算中的典型應用,關鍵在於正確初始化變數、設計終止條件與累加邏輯。初學者可嘗試修改為 for 迴圈或加入輸入驗證以加深理解。