Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Integer Arithmetic

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

like image 865
Stateful Avatar asked Nov 16 '10 18:11

Stateful


4 Answers

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.

like image 86
High Performance Mark Avatar answered Nov 07 '22 03:11

High Performance Mark


An integer divided by an integer is an integer.

so 60/600 is not 0.1, it is 0.

Cast (or declare) some stuff as float instead.

like image 23
Dave DeLong Avatar answered Nov 07 '22 02:11

Dave DeLong


It's doing integer math. 60 / (12 * 50) is 0.1, truncates to 0.

Should work if you force floating point and then cast back to an integer.

int o = (int)(60.0 / ((double) i / 50.0) * 1000.0;

Probably not really necessary to make everything a double.

like image 1
Neth Avatar answered Nov 07 '22 04:11

Neth


Replace:

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

with:

int o = 1200/i;
like image 1
R.. GitHub STOP HELPING ICE Avatar answered Nov 07 '22 02:11

R.. GitHub STOP HELPING ICE