开发者

objective-c divide always returns 0

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 he开发者_如何学Cck, am I crazy?


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.


Since both of these numbers are considered to be integers by the computer, integer math is performed and an integer is returned with no decimals which is 0 (0.06), then converted to float and stored in the variable p1.

A least one number (or both) has to be float to do floating point math, when you append a decimal to a number you tell the computer that the constant is a floating point number.

float p1 = (6.0 / 100);

Or you could typecast it

float p1 = ((float)6 / 100);


Your assignment contains an integer divide, which returns zero if the number you are dividing by is greater. You probably meant to do:

float p1 = (6.0f / 100.0f);


A work around to divide two int variables and get float result.

int x = 5;
int y = 7;

float z = x / y;  // always 0

The fix:

float z = 1.0 * x / y;

Note: if you change the order this solution won't work.

Edit: According to this answer previous answer You can use this

float z = (float) x / y;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜