浮点数小数比较cocos2d

时间:2012-11-17 15:47:59

标签: timer cocos2d-iphone

你好,这里的人是我的问题: 我如何减少只有小数的浮点数? %.1对我来说是最好的,但是当我与另一个像unNumero = 1.7f的浮点数比较时,代码不会这样做。我认为因为浮动数字更多。我怎么能解决这个问题。我需要比较stopCrono的结果和一些随机浮点数,但限制为2位小数。对不起,我的英语不是我的母语。 这是我的代码

- (void)startCrono:(ccTime)delta {

totalTime += delta  ;
currentTime = totalTime;
timeLimit = 2.0f;
[timeLabel setString:[NSString stringWithFormat:@"%.1f ",currentTime ]];
if (currentTime >= timeLimit) {

    [self unschedule:_cmd];
    }

} - (无效)stopCrono:(ccTime)crono2 {

[self unschedule:@selector(startCrono:)];
unNumero = 1.7f;

if(unNumero == currentTime){

    CCLOG(@"OK");
}

}

if staetment不工作当我在1.7停止我的crono时,CClog不能打印OK

1 个答案:

答案 0 :(得分:1)

因为浮点数学不精确,比较两个浮点值以查看它们是否与==运算符相等通常不会产生您期望的结果。我推荐你是Bruce Dawson的this article,它是关于浮点数的优秀系列的一部分,用于理解如何以适当的方式比较浮点值(提示:它比它看起来要难得多) )。