This formula is mathematically correct:
(F - 32) * (5 / 9) + 273.15
But when the C++ compiler translates it into code, this part
(5 / 9)
is treated as an integer division.
Try this:
cout << "(5/9) = " << (5/9) << endl;
Output:
Yes, you read that correctly. 5 divided by 9 gives zero.
The reason is both 5 and 9 are integers, so an integer division is performed. The whole-number part of the answer is kept, and any part after the decimal point is discarded.
If you look back to the formula
(F - 32) * (5 / 9) + 273.15
you can see what is happening now. It simplifies to this:
(F - 32) * 0 + 273.15
Since anything multiplied by zero results in zero, the entire left-hand expression disappears and we are left with just
273.15
A correct way to code this is to make either one or both of 5 and 9 into floating point values. Try this:
cout << "(5.0/9.0) = " << (5.0/9.0) << endl;
Output:
(5.0/9.0) = 0.555556
When a literal value such as 5.0 is used, the compiler treats it as type
double
and carries out the floating-point division as required.
So that's the explanation as to why the mathematically correct formula gave unexpected results.
And finally, this is how to correct it:
(F - 32) * (5.0 / 9.0) + 273.15