0

我有以下代码:

- (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”出现。

我想我是盲人,因为这不应该很复杂。

4

1 回答 1

1

这很可能会发生,因为变量的类型是float:即使它们都打印为5,其中一个实际上可能比另一个略小(例如,4.9999999999999999)。这可能是由于actPlayerNrQ计算方式造成的:例如,如果添加0.150 次,您将不会得到精确的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

要解决此问题,您可以与 epsilon 进行比较,例如

#define EPSILON 1E-8
// 1E-8 stands for 1*10^-8, or 0.00000001
...

if ((actPlayerNrQ - nrMatchQ) < EPSILON && (inactivePlayerNrQ - nrMatchQ) < EPSILON)
    ...
于 2013-04-13T16:13:40.117 回答