I wanted to get the convert from Fahrenheit to Celsius with this program, but it always returns 0. Why?
#include <stdio.h>
int main() {
int fahr = 15, celsius;
celsius = (5 / 9) * (fahr - 32);
printf("%d\n", celsius);
return 0;
}
It seems that the problem is in celsius = (5 / 9) * (fahr - 32);
. I already know that celsius = 5 * (fahr - 32) / 9;
fixes the problem. But why did the first one return zero?
>Solution :
In short, when performing arithmetic operations, C compiler has to choose which number format to use. To do this, it won’t pick the one of the first operand, nor try to guess what the result would be, but will opt for the most precise type of both operand.
In your particular example, (5 / 9)
use two integers, so the result will remain an integer too, thus zero.
A quick way to fix this is to directly specify a decimal in your constant :
(5 / 9.0)