Search code examples
c++floating-pointmultiplicationfractions

C++ multiply float by fraction


just started C++ from a MATLAB background and getting confused.

float farenheit, celcius;
cin >> farenheit;
celcius = (farenheit - 32) * (5 / 9);
cout << "Temperature (c): " << celcius;

why does multiplying by 5/9 not work as expected, but this does?:

float farenheit, celcius;
cin >> farenheit;
celcius = ((farenheit - 32) * 5) / 9);
cout << "Temperature (c): " << celcius;

Thanks!


Solution

  • Thanks everyone,

    C++ interprets 5 and 9 as int values so 5/9 is also an int. 5/9 = 0.566 which is truncated down to 0.

    To fix this, append .0 or .f to the values be interpreted as a double or float respectively.