且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Objective-C:如何检查一个数字是否在两个值之间

更新时间:2023-02-09 23:05:31

除非您的编译器损坏,否则该代码没有任何问题.x

Unless your compiler is broken there is nothing wrong with that code. There is probably something wrong with x

正如 Sascha 在评论中所说,确保 x 不是 NSNumber.这样做的原因是如果 x 是一个 NSNumber 那么存储在其中的值是一个指针,该值可能远高于 100(例如 0x4FBC60),你会想要与 -(int)intValue 进行比较.

As Sascha stated in the comments make sure that x is not an NSNumber. The reason for this is if x is an NSNumber then the value stored in it is a pointer which value would likely be much higher than 100 (0x4FBC60 for example) and you would want to compare against the -(int)intValue.

其他需要考虑的事情是与正确的数据进行比较.虽然隐式数字转换效果很好,但您可能希望使用与数据类型相同的文字比较.

Other things to consider are comparing against the right data. While implicit number conversions work well you may want to use the same literal comparison as your data type.

unsigned long long x = 51ull;
if(x > 50ull && x < 100ull)
{

}