Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ floating-point console output issue

Tags:

c++

io

float x = 384.951257;
std::cout << std::fixed << std::setprecision(6) << x << std::endl;

The output is 384.951263. Why? I'm using gcc.

like image 285
user361633 Avatar asked Feb 16 '26 04:02

user361633


2 Answers

float is usually only 32-bit. With about 3 bits per decimal digit (210 roughly equals 103) that means it can't possibly represent more than about 11 decimal digits, and accounting for other information it also needs to represent, such as magnitude, let's say 6-7 decimal digits. Hey, that's what you got!

Check e.g. Wikipedia for details.

Use double or long double for better precision. double is the default in C++. E.g., the literal 3.14 is of type double.

like image 91
Cheers and hth. - Alf Avatar answered Feb 18 '26 20:02

Cheers and hth. - Alf


Floats have a limited resolution. So it gets rounded when you assing the value to x.

like image 25
tillaert Avatar answered Feb 18 '26 19:02

tillaert