我知道这个问题非常具体,但相信它对任何想了解 Objective-C 计算器工作方式的人都有帮助。
应用程序是这样工作的:按下一个数字;
- (IBAction)numberButtonPressed:(id)sender
{
//Resets label after calculations are shown from previous operations
if (isMainLabelTextTemporary)
{
(mainLabel.text = @"0");
isMainLabelTextTemporary = NO;
}
NSString *numString = ((UIButton*)sender).titleLabel.text;
//Get the string from the button label and main label
mainLabel.text = [mainLabelString stringByAppendingFormat:numString];
}
按下一个操作数,
- (IBAction)operandPressed:(id)sender
{
//Calculate from previous operand
[self calculate];
//Get the NEW operand from the button pressed
operand = ((UIButton*)sender).titleLabel.text;
}
按下另一个数字,当按下等于时,三个被计算到结果中;
- (IBAction)equalsPressed:(id)sender
{
[self calculate];
//reset operand
operand = @"";
}
计算方法是
- (void)calculate
{
//Get the current value on screen
double currentValue = [mainLabel.text doubleValue];
// If we already have a value stored and the current # is not 0, operate the values
if (lastKnownValue != 0 && currentValue != 0)
{
if ([operand isEqualToString:@"+"])
lastKnownValue += currentValue;
else if ([operand isEqualToString:@"-"])
lastKnownValue -= currentValue;
else if ([operand isEqualToString:@"×"])
lastKnownValue *= currentValue;
else if ([operand isEqualToString:@"/"])
lastKnownValue /= currentValue;
else if ([operand isEqualToString:@"xʸ"])
lastKnownValue = (pow(lastKnownValue, currentValue));
else if ([operand isEqualToString:@"ʸ√x"])
lastKnownValue = (pow(lastKnownValue, 1.0/currentValue));
}
else
lastKnownValue = currentValue;
//Set the new value to the main label
mainLabel.text = [NSString stringWithFormat:@"%F", lastKnownValue];
isMainLabelTextTemporary = YES;
}
清除
- (IBAction)clearPressed:(id)sender
{
lastKnownValue = 0;
mainLabel.text = @"0";
isMainLabelTextTemporary = NO;
operand = @"";
}
计算工作正常,结果显示正确。如果然后您按 clear
并计算其他内容,则不会出现任何问题,但是,如果在显示结果后尝试输入另一个数字,然后用它计算,则会用最后一个结果完成。
多次查看代码,尝试设置 NSLogs
以持续监控值,但没有找到错误,有什么问题吗?
编辑,解决方案:正如 Wain 的回答所暗示的那样,解决方案是重置 lastKnownValue
,在计算并显示结果后这样做,将其设置为 0,以便输入新代码时,代码会覆盖它:
- (IBAction)equalsPressed:(id)sender
{
[self calculate];
//reset operand
operand = @"";
//reset lastKnownValue
lastKnownValue = 0;
}
最佳答案
因为当你不清除最后一组 operand
仍然存在并且 lastKnownValue
和 currentValue
都将存在(因为一个是新的一个是之前的结果)。
我猜混淆是因为你从 operandPressed:
触发计算,所以计算继续“中流”。
考虑建立用户输入的整个计算并将其作为一个整体处理的可能性,而不是单独完成每个部分并修改 lastKnownValue
的值(显然,您执行此操作的能力取决于您想要呈现给用户的界面)。
关于ios - 使用上次结果而不是新值运行的计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20221720/