Question on type conversion
Here's my code:
float result;
开发者_StackOverflow中文版result = 1.0 + 1/2;
NSLog(@"Result = %f", result);
Why is the value of result 1.000000 instead of 1.5?
Thanks
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:
(float)result = (double)1.0 + (int)((int)1 / (int)2);
(float)result = (double)1.0 + (int)0;
(float)result = (double)1.0 + (double)0.0;
(float)result = (double)1.0;
(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:
(float)result = (float)1.0 + (float)((float)1.0 / (float)2);
(float)result = (float)1.0 + (float)0.5;
(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;?
Because 1/2
is 0, because this is being done with integer mathematics.
Try
result = 1.0 + 1.0/2
Replace
result = 1.0 + 1/2;
with
result = 1.0 + 1.0/2.0;
精彩评论