本帖最后由 棉/mg花/x糖 于 2015-3-5 14:52 编辑
急求解决:iOS关于判断两个浮点数整除的解决办法!!!
- /**
- * 判断两个浮点数是否整除
- *
- * @param firstNumber 第一个浮点数(被除数)
- * @param secondNumber 第二个浮点数(除数,不能为0)
- *
- * @return 返回值可判定是否整除
- */
- - (BOOL)judgeDivisibleWithFirstNumber:(CGFloat)firstNumber andSecondNumber:(CGFloat)secondNumber
- {
- // 默认记录为整除
- BOOL isDivisible = YES;
-
- if (secondNumber == 0) {
- return NO;
- }
-
- YBLog(@"firstNumber = %f", firstNumber);
- YBLog(@"secondNumber = %f", secondNumber);
-
- CGFloat result = firstNumber / secondNumber;
-
- YBLog(@"result = %f", result);
- // NSString * resultStr = @"10062.0038";
- NSString * resultStr = [NSString stringWithFormat:@"%f", result];
- YBLog(@"resultStr = %@", resultStr);
-
- NSRange range = [resultStr rangeOfString:@"."];
-
- NSString * subStr = [resultStr substringFromIndex:range.location + 1];
-
- YBLog(@"subStr = %@", subStr);
- YBLog(@"subStr的长度 = %zd", subStr.length);
-
- for (NSInteger index = 0; index < subStr.length; index ++) {
- unichar ch = [subStr characterAtIndex:index];
-
- // 后面的字符中只要有一个不为0,就可判定不能整除,跳出循环
- if ('0' != ch) {
- YBLog(@"不能整除");
- isDivisible = NO;
- break;
- }
- YBLog(@"ch = %d", ch);
- }
-
- // YBLog(@"可以整除");
- return isDivisible;
- }
复制代码 输入1.49,0.01,结果如下:- 2015-03-05 14:46:01.787 [2306:130962] firstNumber = 1.490000
- 2015-03-05 14:46:01.787 [2306:130962] secondNumber = 0.010000
- 2015-03-05 14:46:01.787 [2306:130962] result = 149.000004
- 2015-03-05 14:46:01.788 [2306:130962] resultStr = 149.000004
- 2015-03-05 14:46:01.788 [2306:130962] subStr = 000004
- 2015-03-05 14:46:01.788 [2306:130962] subStr的长度 = 6
- 2015-03-05 14:46:01.788 [2306:130962] ch = 48
- 2015-03-05 14:46:01.788 [2306:130962] ch = 48
- 2015-03-05 14:46:01.789 [2306:130962] ch = 48
- 2015-03-05 14:46:01.789 [2306:130962] ch = 48
- 2015-03-05 14:46:01.789 [2306:130962] ch = 48
- 2015-03-05 14:46:01.789 [2306:130962] 不能整除
复制代码
急求,大神出来帮忙解决一下这个问题。明明能整出,为什么打印不能整除。
|
|