Objective-C Integer Arithmetic

Stateful picture Stateful · Nov 16, 2010 · Viewed 21.4k times · Source

I'm trying to calculate some numbers in an iPhone application.

int i = 12;
int o = (60 / (i * 50)) * 1000;

I would expect o to be 100 (that's milliseconds) in this example but it equals 0 as displayed by NSLog(@"%d", o).

This also equals 0.

int o = 60 / (i * 50) * 1000;

This equals 250,000, which is straight left-to-right math.

int o = 60 / i * 50 * 1000;

What's flying over my head here?

Thanks,
Nick

Answer

High Performance Mark picture High Performance Mark · Nov 16, 2010

In Objective-C / performs integer division on integer arguments, so 4/5 is truncated to 0, 3/2 is truncated to 1, and so on. You probably want to cast some of your numbers to floating-point forms before performing division.

You're also running in to issues with precedence. In the expression

60 / (i * 50) * 1000

the term inside the parentheses is calculated first, so 60 is divided by 600 which produces the result 0. In

60 / i * 50 * 1000

the first operation is to divide 60 by 12 which gives the result 5 and then the multiplications are carried out.