int Cleo_profit = 100;
int Daphne_profit = 100;
while (Cleo_profit < Daphne_profit) {
// 迴圈體
}
問題:Cleo_profit 與 Daphne_profit 初始值均為 100,條件 100 < 100 為 false,迴圈零次執行。
Cleo_profit = 90)。do {
// 迴圈體:更新利潤
Cleo_profit += ...;
Daphne_profit += ...;
} while (Cleo_profit < Daphne_profit);
Cleo_profit 增長超過 Daphne_profit。#include <iostream>
using namespace std;
int main() {
double cleo = 100.0;
double daphne = 100.0;
int year = 0;
do {
cleo *= 1.05; // 複利
daphne += 10.0; // 單利
year++;
cout << "Year " << year << ": Cleo=" << cleo << ", Daphne=" << daphne << endl;
} while (cleo <= daphne);
cout << "After " << year << " years, Cleo exceeds Daphne." << endl;
return 0;
}
while 是先判斷後執行,條件初始為 false 則不進入。do-while 是先執行後判斷,至少執行一次。<= 或設定誤差範圍,避免精度問題導致多跑/少跑一次。