0

I have the following code:

- (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;
}

With the following NSLog output, during two loops:

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

I guess there is something wrong with the If-statement and "&&" as i am not expecting the "MATCH OFF" when it comes.

I guess i am blind as this should not be complicated.

PeterK
  • 4,243
  • 4
  • 44
  • 74

1 Answers1

1

This is very likely happening because the variables are of the type float: even through they both print as 5, one of them may be actually slightly smaller than the other (say, 4.9999999999999999). This could happen because of the way actPlayerNrQ is calculated: for example, if you add 0.1 fifty times, you would not get exactly a 5.

Here is a link to an example (it is in C, but that part of the language is shared with 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");

This prints

5.000000 < 5.000000 : yes

To fix this, you could compare with an epsilon, for example

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

if ((actPlayerNrQ - nrMatchQ) < EPSILON && (inactivePlayerNrQ - nrMatchQ) < EPSILON)
    ...
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523