When writing a program in C to convert celsius to fahrenheit, the following formula gives the incorrect output:
int fahr = 9 / 5 * celsius + 32;
Now, I understand that this is probably an issue with 9/5 being interpreted as an integer, but what I don't understand is that using double
or float
it still gives the same incorrect output.
Oddly enough the following formula gives the correct output despite also setting the type to int
:
int fahr = celsius / 5 * 9 + 32;
Furthermore, i've noticed even something as simple as the below, when the type is set to double
, still gives the output as 1.0 instead of 1.8:
double x = 9 / 5;
printf("%lf\n", x);
I've read this thread:
C program to convert Fahrenheit to Celsius
but I still don't understand why int fahr = celsius / 5 * 9 + 32;
works but not int fahr = 9/5 * celsius+32;
?