我在编程方面是全新的,对于我第一次尝试应用程序,我正在编写一个基本的计算器。现在,我可以使用所有 4 个运算符(+、-、*、/)进行计算,但如果我再次按下等于,它就会崩溃。如何让它再次运行计算?例如,如果我输入“2+2=4”,我如何按等于第二次产生“6”,然后按第三次产生“8”等等......
这是我到目前为止所拥有的。我正在使用 switch 语句。
-(void)equalsButton:(id)sender
{
second = [display.text integerValue];
int result;
NSArray* components;
switch (operator)
{
case 0:
components = [display.text componentsSeparatedByString:@"+"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first + second;
break;
case 1:
components = [display.text componentsSeparatedByString:@"-"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first - second;
break;
case 2:
components = [display.text componentsSeparatedByString:@"*"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first * second;
break;
case 3:
components = [display.text componentsSeparatedByString:@"/"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first / second;
break;
}
NSString * result1 = [NSString stringWithFormat:@"%i",result];
display.text = result1;
}