【问题标题】:Objective c min max operation目标 c min max 操作
【发布时间】:2015-09-25 04:42:27
【问题描述】:

你能解释一下为什么这个代码:

NSInteger i = -1;
NSUInteger x = 1;
NSLog(@"min = %lu", MIN(i, x));
NSLog(@"max = %lu", MAX(i, x));;

打印 最小值 = 1

最大值 = 18446744073709551615

【问题讨论】:

  • 您正在比较 2 种不同类型的对象... MAX 和 MIN 在内部转换值。

标签: objective-c math


【解决方案1】:

这是因为i 实际上被隐式转换为无符号整数。见here。结果,它滚动到 18446744073709551615。

【讨论】:

    【解决方案2】:

    您比较了两种不同的类型:有符号 (NSInteger) 和无符号 (NSUInteger)。 MIN/MAX 全部转换为无符号整数。

    此外,负的 NSInteger 用 %lu 而不是 %du 打印。因此看到一个很大的数字。

    NSInteger i = -1;
    NSUInteger x = 1;
    NSLog(@"min = %ld", MIN(i, (NSInteger)x));
    NSLog(@"max = %ld", MAX(i, (NSInteger)x));
    

    【讨论】:

      【解决方案3】:

      这是因为 i 被隐式转换为无符号长整数。它是 xcode 处理整数转换方式的一部分。这是一个类似的帖子。 NSUInteger vs NSInteger, int vs unsigned, and similar cases

      【讨论】:

        猜你喜欢
        • 2022-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多