我是编程的全新人物。对于我第一次尝试应用程序,我正在编写一个基本的计算器。现在,我可以使用所有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;
}
答案 0 :(得分:0)
从我收集的内容中,您将该显示字段用作输入和输出。因此,当您第一次计算时,它现在只有结果而您丢失了操作符和第二个操作数,您尝试重新应用于结果。
所以我想说,如果你不想做太多改动,你可以做的一件事是每次计算结果时都将操作符和第二个操作数存储在实例变量中。这样,如果您无法确定运算符,则表示您想要调用最后一个运算符。所以基本上它会在你的switch语句中添加一个新的case:
display.text
作为第一个操作数一旦达到这一点,您可能希望将冗余代码合并到evaluate:(int)operator a:(int)a b:(int)b
方法或类似的东西中,这样您就不必为新的所有运算符重复所有的eval代码案件块。
<强>更新强>
我的工作计算机上没有XCode,所以我无法尝试,加上我没有剩下的代码,但试试这个。它应该适用于+。如果是,请复制其他运营商。
-(void)equalsButton:(id)sender
{
int result;
NSArray* components;
switch (operator)
{
case 0:
components = [display.text componentsSeparatedByString:@"+"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
if([components count] > 1) {
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;
}