gpt4 book ai didi

objective-c - -1 < 4 返回 NO?太奇怪了

转载 作者:行者123 更新时间:2023-12-04 05:15:09 26 4
gpt4 key购买 nike

int counter=-1;
NSArray *pointArray=[[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"1",@"2", nil];
NSString *result=[NSString stringWithFormat:@"%d",counter<pointArray.count-1];

信不信由你结果是0!!!
试试看谁能告诉我为什么???

最佳答案

请注意,以下代码重现了此问题:

#include <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
NSUInteger uns = 4;
int sig = -1;
BOOL cmp = (sig < uns);
NSLog(@"(%d<%zu)=%d", sig, uns, cmp);
}

这个的输出是
 (-1<4)=0

正如已经指出的那样,问题在于您正在比较 intNSUInteger .但请记住,在 64 位系统上, NSUInteger typedef of unsigned long .

我们看到的行为是 usual arithmetic conversion 的结果:

  1. If either operand is of type long double, the other operand is converted to type long double.
  2. If the above condition is not met and either operand is of type double, the other operand is converted to type double.
  3. If the above two conditions are not met and either operand is of type float, the other operand is converted to type float.
  4. If the above three conditions are not met (none of the operands are of floating types), then integral conversions are performed on the operands as follows:
    • If either operand is of type unsigned long, the other operand is converted to type unsigned long.
    • If the above condition is not met and either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
    • If the above two conditions are not met, and either operand is of type long, the other operand is converted to type long.
    • If the above three conditions are not met, and either operand is of type unsigned int, the other operand is converted to type unsigned int.
    • If none of the above conditions are met, both operands are converted to type int.


由于两个操作数都不是浮点类型,我们到达 4. .由于第二个操作数 ( pointArray.count-1 ) 的类型是 NSUInteger ,即类型 unsigned long ,另一个操作数( counter )被转换为类型 unsigned long ,取值 18446744073709551615这确实大于 4 .

关于objective-c - -1 < 4 返回 NO?太奇怪了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14371867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com