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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
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;?