Lunatica
Lunatica

Reputation: 31

Unexpected result in floating point output

The following code:

#include <iostream>
#include <ios>

int main() {
    auto mod = 1e9+7;
    std::cout << mod << '\n';
    std::cout << std::fixed << mod << '\n';
}

outputs:

1e+009
1000000007.000000

I think that in this case, mod is a floating point number and so first one gives 1e+009 as output which may be due to floating point precision. But then after while using std::fixed, why the output is not 1000000000.000000 ?

Upvotes: 0

Views: 201

Answers (1)

Ilya Popov
Ilya Popov

Reputation: 4010

1e9 + 7

This number is exactly representable in double, there is not loss of precision here.

However, when you print it using std::cout << mod, it is printed using default precision, which is 6 decimal digits. Therefore, 7 is not printed.

You can adjust precision of std::cout using std::setprecision manipulator:

#include <iostream>
#include <iomanip>

int main() {
    std::cout << std::setprecision(10) << mod << '\n';
}

will print 1000000007

Upvotes: 6

Related Questions