Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Noob Question! Why does this always return 0?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading