How to prevent rounding error in C ++?

How can I prevent a rounding error in C ++ or fix it?

Example:

float SomeNumber = 999.9999;
cout << SomeNumber << endl;

He prints 1000!

+5
source share
4 answers

You can change the rounding done by coutsetting the precision.

cout.precision(7);
float SomeNumber  = 999.9999;
cout << SomeNumber  << endl;

Alternatively you can use printffrom cstdio.

+4
source

By default, formatted output std::ostreamrounds off floating point values โ€‹โ€‹to six significant decimal digits. You need seven to avoid rounding your number to 1000:

cout << setprecision(7) << SomeNumber << endl;
        ^^^^^^^^^^^^^^^

, , float, 32- IEEE. , double. , 1000, , :

float SomeNumber = 999.99999; // 8 significant figures
cout << setprecision(10) << SomeNumber << endl;
+3

, setprecision iomanip.

float SomeNumber = 999.9999;
std::cout << SomeNumber << std::endl; //outputs 1000
std::cout << std::setprecision (7) << SomeNumber << std::endl; //outputs 999.9999
return 0;

, SomeNumber, 999.9999, ( , float).

+1

, cout, .precision. , :

You cannot avoid such rounding errors using floating point numbers. You need to present your data in a different way. For example, if you want 5 digits of precision, just save it as a long one that represents the number of your smallest units.

those. 5.23524 with an accuracy of 0.00001 can be represented as long (or int, if your range of values โ€‹โ€‹is suitable) as 523524. You know that the units are 0.00001, so you can easily make it work.

0
source

All Articles