-1

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?

TechTycho
  • 134
  • 1
  • 10

3 Answers3

1

The other answers and comments are steering you in the correct direction with regards to integer division vs floating point. But if you want to avoid floating point altogether and still produce a correct answer (as an integer), then structure your equation such that division comes last.

Since (x/y) * z is the same as (x * z)/y, then this holds:

celsius =  (5 * (fahr - 32)) / 9;
selbie
  • 100,020
  • 15
  • 103
  • 173
1

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)
Obsidian
  • 3,719
  • 8
  • 17
  • 30
0

In C, if you do a division between two integer type variables, you get an integer back.

So this:

(5 / 9)

gets a result of 0.555, which is then rounded down. (In C, integer division rounds towards zero.)

If you changed it like this, it would be floating point division instead:

celsius = (5.0 / 9) * (fahr - 32);
Nick ODell
  • 15,465
  • 3
  • 32
  • 66