airismything
airismything

Reputation: 57

Why does C not truncate this?

I'm currently reading the K&R Book on C, I'm currently doing the temperature converter code and it says here that cels = 5 * (fahr-32) / 9; instead of just multiplying it by 5/9 we multiply by 5 and then divide by 9 since it truncates, but my code doesn't truncate it am I doing something wrong or is this a new feature in Modern C? here is my code

#include <stdio.h>

int main(){
    int fahr, cels;
    int lower, upper, step;

    lower = 0;
    upper = 300;
    step = 20;
    fahr = lower;
    while (fahr <= upper) {
        cels = (fahr - 32) * 5/9;
        printf("%d\t%d\n", fahr, cels);
        fahr = fahr + step;
    }
}

Edit: Instead of cels = (fahr - 32) * 5/9; I did cels = 5/9 *(fahr - 32); and it truncates the code. Why does the other one work while the other does not?

Upvotes: 2

Views: 119

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126536

When you do (fahr - 32) * 5/9, that is the same as ((fahr - 32) * 5)/9, since * and / have the same precedence and are left associative. But when you do 5/9 *(fahr - 32), that is the same as (5/9) *(fahr - 32) for the same reason.

In all cases, the integer divide truncates towards 0, so what matters is whether you multiply then divide (which gives you the "correct" result) or divide then mulitply (which always gives you 0 as 5/9 truncates to 0)

Upvotes: 3

Related Questions