สมมติว่าเราได้รับค่า double 3 ค่า ต้องจัดรูปแบบและพิมพ์ดังนี้:
- ค่าที่ 1: พิมพ์ส่วนจำนวนเต็มในรูปแบบฐานสิบหก (hex) ตัวพิมพ์เล็ก
- ค่าที่ 2: พิมพ์ทศนิยม 2 ตำแหน่ง มีเครื่องหมาย + หรือ - ชิดขวา ความกว้าง 15 ตัวอักษร เติม _ ด้านซ้าย
- ค่าที่ 3: พิมพ์ทศนิยม 9 ตำแหน่งในรูปแบบสัญลักษณ์วิทยาศาสตร์ (scientific notation)
เช่น หากอินพุตคือ 256.367, 5783.489, 12.5643295643 ผลลัพธ์จะเป็น:
0x100 _______+5783.49 1.256432956E+01
ขั้นตอนการแก้ปัญหา
- ค่าแรก: ใช้ hex, showbase, nouppercase, left manipulators
- ค่าที่สอง: ใช้ right, fixed, setw(15), setfill('_'), setprecision(2), showpos
- ค่าที่สาม: ใช้ setprecision(9), scientific, uppercase, noshowpos
ตัวอย่างโค้ด
#include <iostream> #include <iomanip> using namespace std; void solve(double a, double b, double c) { cout << hex << showbase << nouppercase << left << (long long) a << endl; cout << right << fixed << setw(15) << setfill('_') << setprecision(2) << showpos << b << endl; cout << setprecision(9) << scientific << uppercase << noshowpos << c << endl; } int main() { solve(256.367, 5783.489, 12.5643295643); return 0; }
อินพุต
256.367, 5783.489, 12.5643295643
เอาต์พุต
0x100 _______+5783.49 1.256432956E+01