#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 ??
#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 ??
because you are doing integer division with s = 10 / 3
Try
s = 10.0f / 3.0f
10/3 is integer division. You need to use 10.0/3 or (float)10/3 or 10/3.0, etc.
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.