I'm experimenting with floating-point output in C++. I have a simple calculation which is 1359270 / 4, in a calculator this results in 339817.5, but when I print it in C++ using std::cout, I get 339818.
Here’s an example:
#include <iostream>
using namespace std;
int main() {
int var1 = 1359270;
int var2 = 4;
cout << static_cast<double>(var1) / var2;
}
I tried to change the variable types to double, but same result.
However, when I used std::setprecision and std::fixed like the example below:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int var1 = 1359270;
int var2 = 4;
cout << fixed << setprecision(1) << static_cast<double>(var1) / var2;
}
This prints the expected result: 339817.5.
Therefore, is this a floating-point precision issue, or is it related to how std::cout formats numbers?
Note: I'm using MinGW-64 GCC C++20 with Code::Blocks IDE In Windows.
As you can see in std::ios_base::precision documentation:
The default precision, as established by std::basic_ios::init, is 6.
This is the reason you see 339818 as the output in the first snippet:
std::cout will use a default of 6 digits, and so 339817.5 is rounded to 339818 when printed.
If your var1 was smaller, e.g. 359270 the exact result value (89817.5) would fit into 6 digits and you would see the exact value with the fraction (see demo).
As you already noticed, you can change the default precision.