Issue with fahrenheit conversion formula in C -


when writing program in c convert celsius fahrenheit, following formula gives incorrect output:

    int fahr = 9 / 5 * celsius + 32; 

now, understand issue 9/5 being interpreted integer, don't understand using double or floatit still gives same incorrect output.

oddly enough following formula gives correct output despite setting type int:

int fahr = celsius / 5 * 9 + 32; 

furthermore, i've noticed simple below, when type set double, still gives output 1.0 instead of 1.8:

 double x = 9 / 5;  printf("%lf\n", x); 

i've read thread:

c program convert fahrenheit celsius

but still don't understand why int fahr = celsius / 5 * 9 + 32; works not int fahr = 9/5 * celsius+32; ?

i still don't understand why int fahr = celsius / 5 * 9 + 32; works not int fahr = 9/5 * celsius+32;

for former, declared celsius float or double, making entire right side evaluate such. assuming used float, works out this:

celsius / 5 * 9 + 32 (celsius / 5.0) * 9 + 32 (celsius / 5.0 * 9.0) + 32 (celsius / 5.0 * 9.0 + 32.0) 

for latter, 9/5 integer arithmetic evaluates 1 before rest of math happens floating point. in case:

9 / 5 * celsius + 32 1 * celsius + 32 // because of this, incorrect answer celsius + 32 celsius + 32.0 

note the type of left hand side irrelevant; right-hand side evaluated without regard that.

update: said celsius int, means happened lucky , test value multiple of 5, giving correct integer result celsius / 5 before doing valid integer arithmetic rest of statement. in second example, being multiple of 5 doesn't you.

in case, know why got lucky, linked question gives answer need to have formula works when celsius isn't multiple of 5: use floating point math, demonstrated in of answers there.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -