Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีพิมพ์ค่า double ด้วยความแม่นยำเต็มที่ (Full Precision) ใน C++


ใช้ manipulators บน cout ตั้งค่าความแม่นยำและรูปแบบ fixed เพื่อแสดงค่า double ด้วย precision สูงสุด

ตัวอย่างโค้ด

#include <iostream>
#include <limits>
using namespace std;

int main() {
    typedef std::numeric_limits<double> dbl;
    double PI = 3.14159265358979;
    cout.precision(dbl::max_digits10);
    cout << "Pi: " << fixed << PI << endl;
    return 0;
}

ผลลัพธ์

Pi: 3.14159265358979

numeric_limits<double>::max_digits10 ให้จำนวนหลักสำคัญสูงสุดที่จำเป็นต้องแสดงเพื่อให้ค่า double กลับมาได้เหมือนเดิม (round-trip)