Somenath Sinha
Somenath Sinha

Reputation: 1214

Why does integer division truncation not occur here?

I was going through the examples in K&R, and stumbled upon this bit of code:

celcius=5 * (fahr-32) / 9;

The author says that we can't use 5/9 since integer division truncation will lead to a value of 0.

The program however, outputs 17 as answer when fahr=0. By my calculations, (0-32)/9 should lead to -3 (due to truncation) and then -3*5 = -15, and NOT -17. Why does this happen?

Upvotes: 1

Views: 88

Answers (2)

user758077
user758077

Reputation:

What the author say is that one should not use

celsius = (fahr-32)*(5/9);


As for your question,

celsius = 5 * (fahr-32) / 9;

is different from

celsius = 5 * ((fahr-32) / 9);

In the later case, you would indeed get -15 when fahr=0.

Upvotes: 3

gnasher729
gnasher729

Reputation: 52592

(0 - 32) is first multiplied by 5, giving -160. -160 / 9 = -17.

Upvotes: 3

Related Questions