POJ 1002 電話號碼映射統計題,邏輯正確但 cout 版本 WA,printf 版本 AC。代碼片段:
// WA 版本
cout << fixed << setprecision(3) << it->first/10000 << "-"
<< fixed << setprecision(4) << it->first%10000 << " " << it->second << endl;
// AC 版本
printf("%03d-%04d %d\n", it->first/10000, it->first%10000, it->second);
fixed + setprecision(3) 對整數 it->first/10000 無效,不會補前導零。輸出 123 而非 001。setprecision(4) 同理,4567 正常,但 7 輸出 7 而非 0007。printf("%03d-%04d") 強制 寬度補零,完全符合題目「3 位區號-4 位號碼」格式要求。#include <iomanip>
cout << setfill('0') << setw(3) << it->first/10000 << "-"
<< setw(4) << it->first%10000 << " " << it->second << endl;
setfill('0') 指定填充字符setw(N) 設定下一個輸出項最小寬度,不足補零setw,因其僅對下一次插入操作有效fixed/scientific 僅影響浮點數,整數格式化靠 setw/setfill。ios::sync_with_stdio(false); cin.tie(nullptr); 加速 cout,但格式控制仍繁瑣。std::format("{:03d}-{:04d} {}", a, b, c) 終結此類問題(需編譯器支援)。教訓:輸出格式是 AC 的一部分,樣例輸出逐字符核對,邊界情況(如 0、最大值)自測驗證。