我猜我是瞎了,因为这应该不复杂。
我有以下代码:
- (NSArray *)checkNormalGameDuelAndMatch:(float)nrDuelQs andNrQPerDuel:(float)nrQPerDuel andNrMatchQ:(float)nrMatchQ andActivePlayer:(float)actPlayerNrQ andInactivePlayer:(float)inactivePlayerNrQ {
NSLog(@"checkNormalGameDuelAndMatch:");
// Check for Matches and Duels to prep for swaps and/or match endings
NSArray *theCheckArray = [[NSArray alloc]init];
NSLog(@"nrDuelQs: %.0f / nrQPerDuel: %.0f", nrDuelQs, nrQPerDuel);
// Check if Match still on
NSLog(@"actPlayerNrQ: %.0f / inactivePlayerNrQ: %.0f / nrMatchQ: %.0f", actPlayerNrQ, inactivePlayerNrQ, nrMatchQ);
if (actPlayerNrQ < nrMatchQ && inactivePlayerNrQ < nrMatchQ) {
// Match is still on
_isMatchStillOn = YES;
// Check if Duel is till on
if (nrDuelQs < nrQPerDuel) {
// Duel is still on
_isDuelStillOn = YES;
NSLog(@"_isDuelStillOn = YES;");
}
else {
_isDuelStillOn = NO;
NSLog(@"_isDuelStillOn = NO;");
}
}
else {
//==MATCH IS OVER==//
_isMatchStillOn = NO;
NSLog(@"MATCH OFF");
}
theCheckArray = @[[NSNumber numberWithBool:_isDuelStillOn], [NSNumber numberWithBool:_isMatchStillOn]];
return theCheckArray;
}
在两个循环中,NSLog输出如下:
checkNormalGameDuelAndMatch:
nrDuelQs: 4 / nrQPerDuel: 5
actPlayerNrQ: 4 / inactivePlayerNrQ: 0 / nrMatchQ: 5
_isDuelStillOn = YES;
checkNormalGameDuelAndMatch:
nrDuelQs: 5 / nrQPerDuel: 5
actPlayerNrQ: 5 / inactivePlayerNrQ: 0 / nrMatchQ: 5
MATCH OFF
我猜if语句和"&&"有问题,因为我不希望"MATCH OFF"出现。
这很可能发生,因为变量的类型是float
:即使它们都打印为5
,其中一个实际上可能比另一个略小(例如,4.9999999999999999
)。这可能是因为actPlayerNrQ
的计算方式:例如,如果您将0.1
加50次,您将不会得到确切的5
。
这里是一个示例的链接(它是用C编写的,但语言的这一部分与Objective C共享)。
float n = 0;
int i = 0;
for (i = 0 ; i != 25 ; i++, n += 0.2);
printf("%f < 5.000000 : %s", n, n < 5.0 ? "yes":"no");
这个打印5.000000 < 5.000000 : yes
要解决这个问题,你可以与一个比较,例如
#define EPSILON 1E-8
// 1E-8 stands for 1*10^-8, or 0.00000001
...
if ((actPlayerNrQ - nrMatchQ) < EPSILON && (inactivePlayerNrQ - nrMatchQ) < EPSILON)
...