Division Problem!

I am dividing numbers like this:

1
2
int cx = x / width*32;
int cy = y / height*32;

Width and height are both 64. x and y are 600. The problem should be 600/2048 and I am expecting a result of zero, but cx and cy contain the value 288 after the operation. Why is this?
Last edited on
closed account (48T7M4Gy)
integer division means that 2/3 = 0 cast the denominator to double or float is one easy way of coping with this drama :)
Associativity of multiplicative operators (*, /, %) is from left to right.
x / width*32 == (x/width) * 32 == (600/64) * 32 == 9 * 32 == 288

This would give the result that you expect:
1
2
// int cx = x / width*32;
int cx = x / (width*32);


closed account (48T7M4Gy)
Oops I missed the reference to 288, story of my life.
Thanks Borges! What an easy fix. I feel silly now.
Topic archived. No new replies allowed.