C ++ floating point issue Cout

#include <iostream>
using namespace std;
int main()
{
        float s;
        s = 10 / 3;
        cout << s << endl;
        cout.precision(4);
        cout << s << endl;
        return 0;

}

      

Why doesn't the output show 3.333 but only 3 ??

+2


source to share


3 answers


because you are doing integer division with s = 10 / 3

Try



s = 10.0f / 3.0f

      

+7


source


The correct way to create a permanent float separation is:

s = 10.f / 3.f; // one of the operands must be a float

      

Without a suffix, f

you perform division double

by providing a warning (from float

to double

).



You can also use one of the operands:

s = static_cast<float>(10) / 3; // use static_cast, not C-style casts

      

The result is correct division.

+4


source


10/3 is an integer division. You need to use 10.0 / 3 or (float) 10/3 or 10 / 3.0 etc.

+2


source







All Articles