-4

I just recently encountered this problem in c++

std::cout << -5.0000004768371582 + 5 << "\n";

This will print -4.76837e-007 even though you would think it would print something like 0.000000476... I know floating points aren't always correct, but I've never seen this before. I've also seen this happen with other numbers.

Why is this. And how could I fix it?

2 Answers2

9

The number is correct, floating point does have some accuracy issues, but in this case it is not the case.

In this case it is just a matter of notation.

-4.76837e-007 means

so it is correct

5

The output you're encountering is known as scientific notation. If you want it to be displayed in fixed point notation, used std::fixed.

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::fixed << std::setprecision(10) << -5.0000004768371582 + 5 << "\n";
}