-2

I am not sure what's going on here, but I have a code sample which is not producing what I expect, here is part in question (just a section):

printf("Now enter a Fahrenheit to convert to Centigrade\n");
fflush(stdout);
scanf("%f",&c);
d = (c-32)*(5/9);
printf("%f\n",c);
printf("Your result in Centigrade is %f\n",d);

The result when I enter 212 for the input is: Your result in Centigrade is 0.000000

When I make a small change:

printf("Now enter a Fahrenheit to convert to Centigrade\n");
fflush(stdout);
scanf("%f",&c);
d = (c-32)*5/9;
printf("%f\n",c);
printf("Your result in Centigrade is %f\n",d);

The result now when I enter 212 for the input is: Your result in Centigrade is 100.00000, which is correct.

In math (a+b) * (c/d) is the same as (a+b) * c / d; so what's going on with the zero result with just the extra parentheses?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153

2 Answers2

3

Since both operands are integers, 5/9 results in 0 since integer division is performed. Use 5./9 instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Here, you need to be careful about two things.

  1. Operator preceedence
  2. Automatic type conversion

First, () operator has higher preceedence than * or / operators.

Second , if an expression contains a float and and int, the int will be automatically converted to float.

Now in your first case what happens is:

  1. (c - 32) is calculated, (here 32 is converted to 32.0 and calculation is done). (say this equals x)
  2. (5/9) is calculated. Here both expressions are int so nothing is converted to float. And for int calculation, 5/9 equals to 0. Say this equals y
  3. Your final answer is calculated as x * y, and since y is 0 , your answer is 0.0.

However in your second case what happens is:

  1. (c - 32) is calculated, (here 32 is converted to 32.0 and calculation is done).
  2. (c - 32) * 5 is calculated. Here 5 is converted to 5.0 and calculation is done. (say this equals x : x is float)
  3. x / 9 is calculated. Here 9 is converted to 9.0 and calculation is done.

So, you can see in second case, there was not multiplication with a 0 - like in the first case - hence you are getting a non-zero (hopefully correct) answer.

sps
  • 2,720
  • 2
  • 19
  • 38