objective-c divide always returns 0

Paul Hart picture Paul Hart · Sep 13, 2010 · Viewed 13k times · Source

Something really weird is happening.

float p1 = (6 / 100);
NSLog(@"p1 = %f", p1);

With those two lines of code I get the following output:

p1 = 0.000000

Why is a simple devide with static numbers not working! I have so much work to do to deal with divide not working! What he heck, am I crazy?

Answer

Pointy picture Pointy · Sep 13, 2010

Those constants are integers, so the math is done with integer math. Try

float p1 = (6.0 / 100.0);

edit — @Stephen Canon wisely points out that since "p1" is a float, there's no reason not to do the whole computation as float:

float p1 = (6.0f / 100.0f);

Now, since those things are both constants, I'd imagine there's a really good chance that the work is going to be done by the compiler anyway. It's also true that because on some modern machines (ie, Intel architecture), the floating-point processor instruction set is sufficiently weird that something that seems like an obvious "optimization" may or may not work out that way. Finally I suppose it might be the case that doing the operation with float constants could (in some cases) give a different result that doing the operation with double values and then casting to float, which if true would probably be the best argument for deciding one way or the other.