Division Problem!

Aug 15, 2016 at 5:08am
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 Aug 15, 2016 at 5:08am
Aug 15, 2016 at 5:16am
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 :)
Aug 15, 2016 at 5:18am
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);


Aug 15, 2016 at 5:40am
closed account (48T7M4Gy)
Oops I missed the reference to 288, story of my life.
Aug 15, 2016 at 2:46pm
Thanks Borges! What an easy fix. I feel silly now.
Topic archived. No new replies allowed.