代碼中`cout << 'a' << ' ' << 'b'...`輸出的是字符字面量`'a'`、`'b'`(即字母a、b),而非變量`a`、`b`的值。正確輸出變量需去掉單引號,並用`setw`格式化間距。本文糾正錯誤並提供標準實現。
// 錯誤
cout << 'a' << ' ' << 'b' << ' ' << 'c' << ' ' << 'd' << ' ' << 'e' << endl;
// 輸出:a b c d e (字符字面量)
// 預期:變量 a,b,c,d,e 的數值
#include
#include // setw
using namespace std;
int main() {
int x;
cout << "請輸入一個五位整數:";
cin >> x;
// 輸入合法性檢查
if (x < 10000 || x > 99999) {
cout << "輸入必須為五位整數!" << endl;
return 1;
}
int a = x / 10000;
int b = x % 10000 / 1000;
int c = x % 1000 / 100;
int d = x % 100 / 10;
int e = x % 10;
// 正確輸出:變量名無引號,setw(3)保證每佔3寬度(含數字本身),右對齊
cout << setw(3) << a << setw(3) << b << setw(3) << c << setw(3) << d << setw(3) << e << endl;
// 輸出示例: 7 5 0 0 0 (輸入 75000)
return 0;
}
| 寫法 | 含義 | 示例 |
|---|---|---|
| `'a'` | 字符字面量,類型`char`,值為ASCII碼97 | 輸出字母 `a` |
| `a` | 變量`a`的值 | 輸出數值如 `7` |
| `"a"` | 字符串字面量,類型`const char[2]` | 輸出字符串 `a` |
void printDigits(int num, int width = 3) {
if (num == 0) { cout << setw(width) << 0; return; }
vector digits;
while (num > 0) { digits.push_back(num % 10); num /= 10; }
for (auto it = digits.rbegin(); it != digits.rend(); ++it)
cout << setw(width) << *it;
cout << endl;
}
核心教訓:單引號是字符字面量,變量名不加引號。格式化輸出用setw,每項前必加 。