0
我嘗試比較浮點值,但我不能這樣做,我用這個代碼:比較浮點值
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
顯然不工作,錯誤在哪裏?代碼似乎是正確的!
你第一次分配到「step」的位置?此外,比較容易(也可能是工作)的比較將是「abs(a - b - step)<0.005」。 – Ryan 2013-04-28 17:13:04
嘗試谷歌搜索「比較浮點數」;有很多棘手的問題。 – 2013-04-28 17:19:23
step是一個參數,不過謝謝!我使用這個比較,現在它工作! – kikko088 2013-04-28 17:29:14