2

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!

2 Answers2

4

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

C++ considers 5 and 9 to be integers and the division is integer division, which means 5/9 = 0 (it returns the quotient).

So use 5.0 and 9.0 if you want them to be floating points.