0
int main (void)
{
    int fahrenheit; // fahrenheit stands for fahrenheit
    double c; // c stands for celsius

    printf("Enter your fahrenheit, we'll covnvert it into celsius! ");
    scanf("%f", &fahrenheit);

    c = 5/9 * (fahrenheit - 32);
    printf("Here is your %f in celsius!.\n");

    return (0);
}

I've followed the code through break points and when it takes in my input the calculations are off, but the formula is correct. Some sort of logic error I can't put my finger on. Please help!

robbmj
  • 16,085
  • 8
  • 38
  • 63

3 Answers3

6

The scanf call uses the wrong format string. You are reading an int so you need it to be:

scanf("%d", &fahrenheit);

The expression 5/9 is evaluated using integer division. In fact the compiler can work it out at compile time. That expression evaluates to 0.

You need to perform floating point division. For instance:

5.0/9

Or:

5/9.0

Or

5.0/9.0

You just need at least one operand to be a floating point value.

Putting this into your expression, you can write:

c = 5.0/9.0 * (fahrenheit - 32);

and obtain the answer that you expect.


Your printf statement is wrong too. You should enable warnings and let the compiler tell you that. You meant to write:

printf("Here is your %f in celsius!.\n", c);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • thank you but I caught my error!! thanks again tho really appreciate it. –  Feb 04 '14 at 23:07
  • If this answer is correct, it should be marked as accepted Victor, even if you caught the error on your own. – nhgrif Feb 04 '14 at 23:28
  • Although the integer division was certainly a problem, `scanf` was being used to read with format `float` into an `int`. Another critical error, and something that would have been obvious with `-Wall`. If you add that to your answer @VictorC really should mark your answer as accepted. – Macattack Feb 04 '14 at 23:40
  • @Macattack Sigh. I got two out of three. It's there now. – David Heffernan Feb 04 '14 at 23:53
1

Integer math versus floating point math.

i = 5/9           // i is equal to 0
d = 5.0/9.0       // d is equal to whatever 5 divided by 9 would actually be

You also need to actually print the value:

printf("Here is your %f in celsius!.\n", c);
nhgrif
  • 61,578
  • 25
  • 134
  • 173
0

Short answer: Operations on integers return integers even if the variable you store the result on is a double. Divisions between integers are truncated.

You should write this instead:

c = 5.0/9.0 * (fahrenheit - 32.0);

Adding a ".0" (or even just a ".") to your constant makes them floating point values.

robbmj
  • 16,085
  • 8
  • 38
  • 63
Taum
  • 2,511
  • 18
  • 18