Search code examples
cgccdouble

C program returning incorrect double value


Code:

int main(){
    double x = 10;
    double Fahrenheit = (x * (9/5)) + 32;
    double Celsius = (5 / 9) * (x - 32);

    printf("%lf\n", Fahrenheit);
    printf("%lf\n", Celsius);
    return 0;
}

output:

42.000000
-0.000000

I have tried re-arranging the formulas, I have also tried using functions but I can't seem to figure out why the ouput is incorrect.

For reference the expected output:

50.00000
-12.22222

re-arranging to:

    double Fahrenheit = (x * 9 / 5) + 32;
    double Celsius = (x - 32) * 5 / 9;

worked!

but so did adding a .0 to all int numbers


Solution

  • The problem is that you are performing the computation as ints (9/5) == 1 when (9.0 / 5.0) == 1.8. Add .0 to all your numbers and you'll be fine