Joe Shamuraq
Joe Shamuraq

Reputation: 1385

Issue with calculation

Can anyone see if there's problem with the way i handle the calculation below? I seemed to be getting "You scored 0" at runtime even when the answer is actually correct.

- (void)countGain{
int gain = 0;
int percentage;
if ([answer objectForKey:@"1"] == [usrAnswer objectForKey:@"1"]) {
    gain += 1;

}
percentage = (gain / 10) * 100;

NSString *scored = [[NSString alloc] initWithFormat:@"You scored %d",percentage];
score.text = scored;
rangenans.text = [answer objectForKey:@"1"];

[scored release];

}

Upvotes: 0

Views: 67

Answers (3)

mmmmmm
mmmmmm

Reputation: 32661

The problem is that you are trying to compare NSStrings and == compares the assresses of strings. You want to compare their values

e.g.

NSString *correct = @"Yes";
NSString *answer = ..... from some entry;

Then these two NSStrings will point to different bits of memory.

to compre with the user replied you need to compare values using the isEqualToString: method

e.g. gain += [correct isEqualToString:answer] ? 1 : 0;

In your code == failed each time so gain was always 0. So the int division problem never occureed - but it would have when gain became 1 etc.

Upvotes: 0

Jakub
Jakub

Reputation: 13860

What is the point doing:

percentage = (gain / 10) * 100;

Use

percentage = gain * 10;

Rest looks good. You shouldn't divide integers. What if you get 3/10 and this is int value?

In condition change

if([answer objectForKey:@"1"] == [usrAnswer objectForKey:@"1"])

To:

if([[answer objectForKey:@"1"] isEqualToString:[usrAnswer objectForKey:@"1"]])

Upvotes: 1

MByD
MByD

Reputation: 137312

This is integer arithmetic. Try:

percentage = gain * 10;

or

percentage = (gain * 10 ) / 100;

or

percentage = ((float)gain / 10) * 100;

Note that in any of the above, you only have 10 options for the "percentage", so percentage = gain * 10; is the simpler.

Upvotes: 1

Related Questions