Ann Ann - 2 years ago 37
C++ Question

There are wrong answer when cout the long double value, C++

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
const long double longDoublePI = 3.141592653589793238;
cout << setw(16) << "longDoublePI = " << setprecision(numeric_limits<long double>::digits10 + 1) << longDoublePI << endl;

return 0;

But the result output is:

longDoublePI = 3.141592653589793116

Why the answer is wrong?

Answer Source

Because, although longDoublePI is a long double, the literal from which you initialised it is only a double, which does not have as much precision.

You can use this instead:

const long double longDoublePI = 3.141592653589793238L;
//                                                   ^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download