我知道這個問題非常具體,但是相信它對任何想學習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 = @"";
}
Calculate方法是
- (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
來持續監視值,但沒有發現錯誤的運氣,什麼是錯誤?
編輯,解決方案:由於在韋恩的回答暗示,該解決方案是重新lastKnownValue
,結果經過這樣的計算和顯示,將其設置爲0,這樣的代碼覆蓋它在進入新時:
- (IBAction)equalsPressed:(id)sender
{
[self calculate];
//reset operand
operand = @"";
//reset lastKnownValue
lastKnownValue = 0;
}
非常感謝!瞭解,我會盡快嘗試並報告結果! –
太棒了!是的,只需將所有按鈕和數字設置爲單個公式字符串,就可以使其更簡單!再次感謝:) –
看看'NSExpression'和它可以做些什麼來幫助你。 – Wain