【问题标题】:NSNumber doubleValue 0 doesn't return exactly 0NSNumber doubleValue 0 不完全返回 0
【发布时间】:2013-01-02 10:42:51
【问题描述】:

我正在处理一个 NSNumber 的 NSMutableArray 并且遇到了一个奇怪的错误。 [NSNumber doubleValue](使用双 0 构造)似乎不等于 0.0。

错误出现在有史以来最简单的函数中:max 函数。

- (double) maxValY{
    double max = DBL_MIN;
    for (NSNumber *doubleNumber in arrayNumbers) {
            if (max<[doubleNumber doubleValue]){
                max = [doubleNumber doubleValue];
            }

    }

    NSLog(@"max %f",max);
    if(max <=0.0){
        NSLog(@"max is equal to 0");
        return 1;
    }else{
        NSLog(@"max is not equal to 0");
    }

    return max;
}

控制台打印:

2013-01-02 11:27:56.208 myApp[1920:c07] max 0.000000
2013-01-02 11:27:56.210 myApp[1920:c07] max is not equal to 0

【问题讨论】:

  • 如果你在NSLog 调用中使用%lf 会发生什么?
  • 我刚刚做了,控制台打印了同样的内容:code2013-01-02 11:50:03.208 myApp[2014:c07] max 0.000000
  • if(max
  • @Krishnabhadra 这是一个关于我在学校学习的理论的非常有趣的链接。更新仍然很有帮助 thx :)。所以如果我写“if(max

标签: ios nsnumber


【解决方案1】:

这不是错误:它是双精度。对于浮点数,您看到的不一定是您得到的。这个问题有更多信息:

Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?

如果您只关心一个数字是等于还是大于零,那么最简单的解决方案就是转换为整数。还有其他更复杂的替代方案:我链接到的答案有一些。有人在 cmets 中为您提供的有关浮点数学的链接也可能会有所帮助。

【讨论】:

  • 谢谢,两个链接都有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 2020-12-22
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多