Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Cout floating point problem

#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 ??

like image 897
gujo Avatar asked May 01 '26 05:05

gujo


2 Answers

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

Try

s = 10.0f / 3.0f
like image 174
jcopenha Avatar answered May 02 '26 17:05

jcopenha


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.

like image 22
GManNickG Avatar answered May 02 '26 18:05

GManNickG