在手寫 itoa 函數將整數轉為字符串時,核心代碼如下:
do {
s[i++] = n % 10 + '0';
n /= 10;
} while (n > 0);
初學者常問:為什麼要加 `'0'`?不加行不行?
在 ASCII 碼表中,字符 '0' 到 '9' 的編碼是連續遞增的:
'0' = 48'1' = 49'9' = 57當我們得到一個個位數字 d = n % 10(範圍 0~9)時,該數字對應的字符編碼 = '0' 的編碼 + d。因此 d + '0' 正好得到字符 '0'~'9' 的 ASCII 值。
n % 10 的結果是整數 0~9,直接存入 char 數組會被當作控制字符(如 0 = NULL, 1 = SOH, 2 = STX…),而非可打印數字字符。輸出時會顯示亂碼或無可見字符。
#include <stdio.h>
void to_str(int n) {
char s[12]; // 足夠容納 32 位整數含符號
int i = 0, sign = n;
if (sign < 0) n = -n; // 記錄符號,轉正
do {
s[i++] = n % 10 + '0'; // 關鍵步驟:數字轉字符
} while ((n /= 10) > 0);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
// 逆序輸出
while (i--) putchar(s[i]);
}
int main() {
int x;
scanf("%d", &x);
to_str(x);
return 0;
}
實際開發中推薦使用標準庫 sprintf(buf, "%d", n) 或 snprintf,更安全、可移植,且支援各種進制與格式化。