views:

155

answers:

3

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?

+11  A: 
Pointy
thanks, that was it.
Paul Hart
You should actually accept the answer if it answered your question.
imaginaryboy
But use single-precision literals to avoid an unnecessary conversion from double to single: `float p1 = 6.0f / 100.0f`
Stephen Canon
Yes, thanks @Stephen that's a great idea.
Pointy
+3  A: 

Your assignment contains an integer divide, which returns zero. You probably meant to do:

float p1 = (6.0f / 100.0f);
stony74
+3  A: 

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);
oddi