比较浮动值

时间:2013-04-28 17:08:45

标签: objective-c

我尝试比较浮点值,但我不能这样做,我使用这段代码:

float a = [[array objectAtIndex:(i+1)] floatValue];
float b = [[array objectAtIndex:(i)] floatValue];

a = [[NSString stringWithFormat:@"%.2f",a] floatValue];
b = [[NSString stringWithFormat:@"%.2f",b] floatValue];
step = [[NSString stringWithFormat:@"%.2f",step] floatValue];

float newStep = a-b;

if (newStep != step) {
      NSLog(@"NewStep: %f Step: %f",newStep,step);
}

这是输出:

2013-04-28 19:07:57.396 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 2.420000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
2013-04-28 19:07:57.397 Pro[24265:c07] NewStep: 0.220000 Step: 0.220000
显然不行,哪里出错?代码似乎是正确的!

1 个答案:

答案 0 :(得分:3)

永远不要比较浮点变量的相等性!由于精度有限,浮点数仅是近似值。使用

if (fabs(a-b)<0.0001) {...

或类似的东西,如果你想检查是否相等。