Reputation: 11
I have some logic problem about this calculator. When I push the "=" after first time executive it'll execute twice with same operand.
For example:
"1"+"2"="3"
"3" + "2", then output -> "5" before I press another operands.
Here is the source code:
https://drive.google.com/file/d/0B1a-AefbM9rOUTdyVmdJOWhNNnc/view?usp=sharing
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var MiddleTyping = false
@IBAction func appandDigit(sender: UIButton) {
let digit = sender.currentTitle!
if MiddleTyping{
display.text = display.text! + digit
}else{
display.text = digit
MiddleTyping = true
}
}
var operandStack = [Double]()
var binaryoperation = [String]();
var firstTimeInputNumber = true
var displayValue: Double{
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
MiddleTyping = false
}
}
@IBAction func Operate(sender: UIButton) {
MiddleTyping = false
var equalOperand = ""
var Operation = ""
if sender.currentTitle == "="{
equalOperand = binaryoperation.last ?? ""
}else{
Operation = sender.currentTitle!
}
if operandStack.count == 1 && binaryoperation.count != 0{
operandStack.append(displayValue)
}
if operandStack.count == 2{
if equalOperand == binaryoperation.last ?? "" {
switch equalOperand{
case "×":
displayValue = operandStack[0] * operandStack[1]
operandStack[0] = displayValue
case "÷":
displayValue = operandStack[0] / operandStack[1]
operandStack[0] = displayValue
case "+":
displayValue = operandStack[0] + operandStack[1]
operandStack[0] = displayValue
case "−":
displayValue = operandStack[0] - operandStack[1]
operandStack[0] = displayValue
default: break
}
}else{
let Operation = binaryoperation.last ?? "";
switch Operation {
case "×":
displayValue = operandStack[0] * operandStack[1]
operandStack[0] = displayValue
operandStack.removeLast()
case "÷":
displayValue = operandStack[0] / operandStack[1]
operandStack[0] = displayValue
operandStack.removeLast()
case "+":
displayValue = operandStack[0] + operandStack[1]
operandStack[0] = displayValue
operandStack.removeLast()
case "−":
displayValue = operandStack[0] - operandStack[1]
operandStack[0] = displayValue
operandStack.removeLast()
default: break
}
}
}
if displayValue != 0 {
if firstTimeInputNumber{
operandStack.append(displayValue)
}
firstTimeInputNumber = false
}
if Operation != ""{
binaryoperation.append(Operation)
}
println("push op \(operandStack)")
println("push op \(binaryoperation)")
}
@IBAction func ClearButton() {
operandStack.removeAll()
binaryoperation.removeAll()
display.text = "0"
firstTimeInputNumber = true
MiddleTyping = false
}
}
Upvotes: 1
Views: 2814
Reputation: 512
All I can image is the conditionbinaryoperation.count != 0
may be
binaryoperation.count == 1
, that is, you don't remove the operator when you perform calculate
Upvotes: 0