Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent rounding error in c++?

Tags:

c++

rounding

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

Example:

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

It prints out 1000!

like image 883
Some Stranger Avatar asked Sep 28 '12 14:09

Some Stranger


People also ask

How do I stop rounding in C++?

you need to include <iomanip> and use the std::setprecision manipulator. To get the level of accuracy you want you will need to use double s rather than float s.

What causes a rounding error?

Rounding errors are due to inexactness in the representation of real numbers and the arithmetic operations done with them. This is a form of quantization error.


1 Answers

You can alter the rounding done by cout by setting the precision.

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

Alternatively, you can use printf from cstdio.

like image 65
cyon Avatar answered Oct 29 '22 15:10

cyon