2012-05-07 110 views
0

我試圖計算從NSMutableArray中檢索到的2個值,但運行時出現錯誤,指出算術計算的方式。算術計算出錯

該插入值的代碼:

NSString *lastEx = @"None"; 
int lastScore = 0; 
int tries = 0; 
int total_score = 0; 
int avg = 0; 
int credit = 100; 

[data addObject:lastEx]; 
[data addObject:[NSNumber numberWithInt:lastScore]]; 
[data addObject:[NSNumber numberWithInt:tries]]; 
[data addObject:[NSNumber numberWithInt:total_score]]; 
[data addObject:[NSNumber numberWithInt:avg]]; 
[data addObject:[NSNumber numberWithInt:credit]]; 

代碼檢索:

NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile:path]; 

previousExercise.text = [savedStock objectAtIndex:0]; 

NSString *lastScoring = [NSString stringWithFormat:@"%d", [[savedStock objectAtIndex:1] intValue]]; 
previousScore.text = lastScoring; 

NSString *totalTries = [NSString stringWithFormat:@"%d", [[savedStock objectAtIndex:2] intValue]]; 
attempts.text = totalTries; 

NSString *average = [NSString stringWithFormat:@"%d", [[savedStock objectAtIndex:4] intValue]]; 
avgScore.text = average; 

int totalScore = [[savedStock objectAtIndex:3] intValue]; 
int numberOfTries = [[savedStock objectAtIndex:2] intValue]; 
int avg; 

avg = ((totalScore/numberOfTries) * 100); 

NSString *rem_credit = [NSString stringWithFormat:@"%d", [[savedStock objectAtIndex:5] intValue]]; 
credits.text = rem_credit; 

錯誤是=>avg = ((totalScore/numberOfTries) * 100);

感謝名單的預先計算...

回答

4

tries爲0,所以int numberOfTries = [[savedStock objectAtIndex:2] intValue]; assi gns 0到numberOfTries以及整數除0引起算術錯誤。

考慮:

avg = (numberOfTries == 0) ? 0 : ((totalScore/numberOfTries) * 100);