OC operator in `/` problems caused by

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 / nis 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 = 18446744073709551516is: .

At this point you should have thought of how it happens, this is the type of OC in operator automatically upgrade function caused. m2 / nM2 in the calculation will be converted to the first NSUIntegertype and then calculated.

The solution:
we want the result m2 / n = -50, so it is necessary to make n type conversion, will m2 / nbe changed m2 / (NSInteger)nto.

Reproduced in: https: //www.jianshu.com/p/d254341f0276

Guess you like

Origin blog.csdn.net/weixin_33811961/article/details/91231467