int itoa(int n, char s[]); // 將整數 n 轉為字串存入 s,回傳字串長度(或 void)
#includestatic int idx = 0; // 靜態區域變數,避免全域污染 void itoa_rec(int n, char s[]) { if (n < 0) { // 處理負數 s[idx++] = '-'; n = -n; } if (n < 10) { s[idx++] = n + '0'; } else { itoa_rec(n / 10, s); // 先遞迴處理高位 s[idx++] = n % 10 + '0'; // 再處理當前低位 } s[idx] = '\0'; // 結束符 } int main() { char s[20]; int num; printf("Enter integer: "); scanf("%d", &num); idx = 0; // 每次呼叫前重置 itoa_rec(num, s); printf("String: %s\n", s); return 0; }
| 原始碼問題 | 修正 |
|---|---|
| 負數未處理 | 加入 `n<0` 判斷,輸出 `-` 並取絕對值 |
| 全域 `i` 未重置 | 改為 `static` 區域變數,`main` 中手動 `idx=0` |
| 遞迴順序邏輯輕微錯誤 | 先遞迴 `n/10`,再寫 `n%10`,確保高位在前 |
| 缺少 `\0` 結束 | 每次寫入後 `s[idx]='\0'` |
void itoa_iter(int n, char s[]) {
int i = 0, sign = n;
if (n < 0) n = -n;
do {
s[i++] = n % 10 + '0';
} while (n /= 10);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
// 反轉字串
for (int l = 0, r = i-1; l < r; l++, r--) {
char t = s[l]; s[l] = s[r]; s[r] = t;
}
}
整數轉字串核心是**「除 10 取餘、逆序輸出」**。遞迴利用呼叫堆疊自動反序,迭代需手動反轉字串。注意負數處理、索引重置、結束符寫入三大細節。