views:

224

answers:

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

}

Why the output does not show 3.333 but only 3 ??

+4  A: 

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

Try

s = 10.0f / 3.0f
jcopenha
Close, but now that's double.
GMan
how about now ?
jcopenha
Righto. :P [15chars]
GMan
I would have done the division as double. Let the compiler truncate only when it required (at the point of assignment).
Martin York
+2  A: 

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

leiz
Use C++ casts, like `static_cast`
GMan
Or ctor syntax, like `float(3)`
MSalters
+2  A: 

The correct way to do a constant float division is:

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

Without the f suffix, you are doing double division, giving a warning (from float to double).

You can also cast one of the operands:

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

Resulting in the correct division.

GMan