十進制 `n` 轉八進制:`n % 8` 為最低位,`n / 8` 遞歸處理高位,最後反序輸出。
#include
#include
using namespace std;
void toOctal(int n, string &result) {
if (n == 0) return; // 基準:商為 0 結束
int rem = n % 8;
toOctal(n / 8, result); // 先處理高位
result += char('0' + rem); // 回溯時拼接低位 → 自然正序
}
int main() {
int x;
cout << "輸入十進制正整數: ";
cin >> x;
if (x == 0) { cout << "0\n"; return 0; }
string result;
toOctal(x, result);
cout << "八進制: " << result << endl;
return 0;
}
string toOctalIter(int n) {
if (n == 0) return "0";
string s;
while (n) { s = char('0' + n % 8) + s; n /= 8; }
return s;
}
遞歸版本更能體現「分解問題、合併結果」的遞歸思維。