2013-11-26 30 views
0

我知道這個問題非常具體,但是相信它對任何想學習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; 
} 

回答

3

因爲當你不清除最後一組operand仍然存在和lastKnownValuecurrentValue都將存在(因爲一個是新的,一個是以前的結果)。

我猜混亂是因爲你從operandPressed:觸發計算,所以計算繼續'中流'。

考慮建立用戶輸入的整個計算並將其作爲一個整體進行處理的可能性,而不是單獨完成每個部分並修改lastKnownValue的值(顯然,您的能力取決於您希望呈現的界面給用戶)。

+0

非常感謝!瞭解,我會盡快嘗試並報告結果! –

+0

太棒了!是的,只需將所有按鈕和數字設置爲單個公式字符串,就可以使其更簡單!再次感謝:) –

+1

看看'NSExpression'和它可以做些什麼來幫助你。 – Wain

相關問題