Problem Description:
See the following code to guess what operating results?
NSInteger m1 = 100;
NSInteger m2 = -100;
NSUInteger n = 2;
NSLog(@"m1 / n = %ld", m1 / n);
NSLog(@"m2 / n = %ld", m2 / n);
Analysis:
This problem seems very simple, but there is a pit, little attention will fall into.
The output of the above code:
m1 / n = 50
m2 / n = 9223372036854775758
So why m2 / n
is not equal to -50 it? If this print NSLog(@"m2 = %lu", m2);
what it will output?
In fact, NSLog(@"m2 = %lu", m2);
the output m2 = 18446744073709551516
is: .
At this point you should have thought of how it happens, this is the type of OC in operator automatically upgrade function caused. m2 / n
M2 in the calculation will be converted to the first NSUInteger
type and then calculated.
The solution:
we want the result m2 / n = -50
, so it is necessary to make n type conversion, will m2 / n
be changed m2 / (NSInteger)n
to.
Reproduced in: https: //www.jianshu.com/p/d254341f0276