0

Here's my code:

float result;
result = 1.0 + 1/2;
NSLog(@"Result = %f", result);

Why is the value of result 1.000000 instead of 1.5?

Thanks

3 Answers 3

3

That is how C compiler rolls. Objective-C is a super thin layer on top of C, so knowing how your C works is good.

All expressions are evaluated according to operator precedence, and types are never promoted or demoted until the last minute. This is how C can ensure as correct results as possible.

So the evaluation steps for this:

float result = 1.0 + 1/2;

Is really:

  1. (float)result = (double)1.0 + (int)((int)1 / (int)2);
  2. (float)result = (double)1.0 + (int)0;
  3. (float)result = (double)1.0 + (double)0.0;
  4. (float)result = (double)1.0;
  5. (float)result = (float)1.0;

What you want is this expression:

float result = 1.0f + 1.0f/2.0f;

Then you end up with this evaluation:

  1. (float)result = (float)1.0 + (float)((float)1.0 / (float)2);
  2. (float)result = (float)1.0 + (float)0.5;
  3. (float)result = (float)1.5;

Much less work for the CPU, and you get what you expect. The speed boost is only noticeable if you use actual variables, not constants. In reality your original statement, and my revised statements will be optimized by the compiler as:

  • (float)result = (float)1;
  • (float)result = (float)1.5;?
3

Because 1/2 is 0, because this is being done with integer mathematics.

Try

result = 1.0 + 1.0/2
0

Replace

result = 1.0 + 1/2;

with

result = 1.0 + 1.0/2.0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.