浮点数不准,这个貌似基本都知道。但是在开发中很多人没有对它的使用产生警觉。如果你在开发iOS应用,你可能使用过如下代码判断系统版本:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { //something support for ios7 } |
这样一段代码也的确工作良好,但是注意了如果你把比较的数值改为7.1,那么很有可能就会出问题。
浮点数不准
这一篇博文从二进制的表示方面说明了为什么浮点数不准,讲的很好,感兴趣的可以学习学习,学习这些感觉还是很有用的,也可以帮助我们定位一些诡异的问题。
在精确的比较中不要使用float
文章开头的系统版本的比较就是一个典型的例子,我们可以通过其他方法实现比较:
if ([[[UIDevice currentDevice] systemVersion] compare:@"7.1"] != NSOrderedAscending) { //something support for ios7 } |
- NSString 两个字符串的比较,用 a compare:b 来比,得出的结果分3种
- 1. 26个字母比较 越靠后面 越大
- NSString *a = @"qweqwe";
- NSString *b = @"qweasd";
- BOOL result = [a compare:b];
- if (result == NSOrderedSame) { // NSOrderedSame = 0 完全一样
- NSLog(@"a = b");
- }else if(result == NSOrderedAscending) // NSOrderedAscending = -1
- NSLog(@"a < b");
- else{ //NSOrderedDescending = +1
- NSLog(@"a > b");
- }
- 2011-07-05 15:04:33.951 Q[5180:207] a > b
- 2.比较数字或者符号,或者字母 什么都行
- NSString *a = @"1.0.30qweqwe";
- NSString *b = @"1.0.45qweasd";
- BOOL result = [a compare:b];
- if (result == NSOrderedSame) { // NSOrderedSame = 0 完全一样
- NSLog(@"a = b");
- }else if(result == NSOrderedAscending) // NSOrderedAscending = -1
- NSLog(@"a < b");
- else{ //NSOrderedDescending = +1
- NSLog(@"a > b");
- }
- 2011-07-05 15:05:13.175 Q[5209:207] a < b
- 3.不考虑大小写比较字符串
- [a caseInsensitiveCompare:b]
- - (void)viewDidLoad
- {
- NSString *a = @"i love my boyfriend.";
- NSString *b = @"I Love My Boyfriend.";
- NSLog(@" \n a: %@ \n",a);
- NSLog(@" \n b: %@ \n",a);
- BOOL result = [a caseInsensitiveCompare:b] == NSOrderedSame;
- }
- // result = (BOOL) YES;
- 4.不考虑大小写比较字符串
- [a caseInsensitiveCompare:b]
- - (void)viewDidLoad
- {
- NSString *a = @"i love my boyfriend.";
- NSString *b = @"Little baby.";
- NSLog(@" \n a: %@ \n",a);
- NSLog(@" \n b: %@ \n",a);
- BOOL result = [a caseInsensitiveCompare:b] == NSOrderedAscending;
- }
- //result = (BOOL) YES;
- 5. 有选择的比较大小 [a compare:b options:NSCaseInsensitiveSearch|NSNumericSearch]
- - (void)viewDidLoad
- {
- NSString *a = @"i love my boyfriend.";
- NSString *b = @"I Love My Boyfriend.";
- NSLog(@" \n a: %@ \n",a);
- NSLog(@" \n b: %@ \n",b);
- BOOL result = [a compare:b options:NSCaseInsensitiveSearch|NSNumericSearch] == NSOrderedSame;
- }
- //result = (BOOL)YES;
- NSCaseInsensitiveSearch 忽略大小写的比较字符串
- NSNumericSearch 比较字符串的个数
- NSLiteralSearch 区分大小写,进行完全比较
时间: 2024-11-05 19:04:20