【发布时间】:2013-11-26 15:48:33
【问题描述】:
我知道这个问题非常具体,但相信它对任何想了解 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不断监控数值,但没能找到错误,有什么问题吗?
EDIT,解决方案:正如 Wain 的回答所暗示的那样,解决方案是重置 lastKnownValue,在计算和显示结果后这样做,将其设置为 0,以便代码在输入新的:
- (IBAction)equalsPressed:(id)sender
{
[self calculate];
//reset operand
operand = @"";
//reset lastKnownValue
lastKnownValue = 0;
}
【问题讨论】:
标签: ios objective-c calculator