Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 heck, am I crazy?

like image 633
Paul Hart Avatar asked Sep 13 '10 16:09

Paul Hart


4 Answers

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.

like image 98
Pointy Avatar answered Nov 20 '22 08:11

Pointy


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);
like image 36
oddi Avatar answered Nov 20 '22 06:11

oddi


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);
like image 9
stony74 Avatar answered Nov 20 '22 07:11

stony74


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;
like image 1
Khaled Annajar Avatar answered Nov 20 '22 08:11

Khaled Annajar