#import "Calculator.h"
@implementation Calculator
- (long) calcNumbers:(NSString *)myOperator andNumberOne:(NSString *)numberOne andNumberTwo:(NSString *)numberTwo {
long result;
if ([myOperator isEqualToString:@"+"]){
result = [numberOne integerValue] + [numberTwo integerValue];
} else if ([myOperator isEqualToString:@"-"]) {
result = [numberOne integerValue] - [numberTwo integerValue];
} else if ([myOperator isEqualToString:@"*"]){
result = [numberOne integerValue] * [numberTwo integerValue];
} else if ([myOperator isEqualToString:@"/"]) {
result = [numberOne integerValue] / [numberTwo integerValue];
} else {
result = [numberOne integerValue] % [numberTwo integerValue];
}
return result;
}
- (long) postFix:(NSMutableArray *)symbols
{
NSMutableArray * newSymbols = [[NSMutableArray alloc]init];
NSString * operatorSigns = @"*/%";
long result = 0;
for (int i = 0; i < symbols.count; i++){
// operand
if (i%2 == 0){
[newSymbols addObject:symbols[i]];
} else { // operator
if ([operatorSigns containsString:symbols[i]]){
result = [self calcNumbers:symbols[i] andNumberOne:symbols[i-1] andNumberTwo:symbols[i+1]];
[newSymbols insertObject:[NSNumber numberWithLong:result] atIndex:i-1];
i = i + 1;
} else {
[newSymbols addObject:symbols[i]];
}
}
}
for (int i = 0; i < newSymbols.count; i++){
if (i%2 == 1){
result = [self calcNumbers:newSymbols[i] andNumberOne:newSymbols[i-1] andNumberTwo:newSymbols[i+1]];
}
}
return result;
}
@end
这是我的班级。我想在命令行中运行RPN计算器。但在calcNumbers方法中,存在EXC_Arithmetic错误。我认为asterisk正在作为(所有)unix_command工作。我怎样才能解决这个问题?提前致谢
答案 0 :(得分:0)
我不认为你现在在postFix
做的事情是正确的,我甚至不知道你想要做什么。
发生崩溃是因为您要向calcNumbers
发送错误值。坏值是指意外顺序的值。
例如,如果myOperator
为@"10"
且numberTwo
为*
,则您将进入else
分支:
result = [numberOne integerValue] % [numberTwo integerValue];
你将被划分(计算模数)为零,这将导致崩溃(你不能除以零)。
如何找到问题(不是实际解决方案):
添加
NSLog(@"Operator %@, operands: %@, %@", myOperator, numberOne, numberTwo);
这应该可以帮助您查看传递给您的函数的值并找到问题。