我有此代码:
class MainViewController: UIViewController {
@IBOutlet weak var summaryLbl: UILabel!
var actualNumber: Double = 0
var previousNumber: Double = 0
var operationMath: Bool = false
var operation = 0
@IBAction func numberPressed(_ sender: UIButton) {
if operationMath == true {
summaryLbl.text = String(sender.tag)
actualNumber = Double(summaryLbl.text!)!
operationMath = false
} else {
if summaryLbl.text == "0" {
summaryLbl.text = ""
}
summaryLbl.text = summaryLbl.text! + String(sender.tag)
actualNumber = Double(summaryLbl.text!)!
}
}
@IBAction func buttons(_ sender: UIButton) {
if summaryLbl.text != "" && sender.tag != 10 && sender.tag != 17 {
previousNumber = Double(summaryLbl.text!)!
if sender.tag == 13 {
summaryLbl.text = "/"
} else if sender.tag == 14 {
summaryLbl.text = "x"
} else if sender.tag == 15 {
summaryLbl.text = "-"
} else if sender.tag == 16 {
summaryLbl.text = "+"
} else if sender.tag == 11 {
var number: Double = Double(summaryLbl.text!)!
number.negate()
let rounded = number.rounded()
summaryLbl.text = String(rounded).replacingOccurrences(of: ".0", with: "", options: .literal, range: nil)
}
operation = sender.tag
operationMath = true
} else if sender.tag == 17 {
var result: Double = 0
var rounded: Double = 0
if operation == 13 {
result = previousNumber / actualNumber
} else if operation == 14 {
result = previousNumber * actualNumber
} else if operation == 15 {
result = previousNumber - actualNumber
} else if operation == 16 {
result = previousNumber + actualNumber
} else if operation == 12 {
result = previousNumber.truncatingRemainder(dividingBy: actualNumber)
}
rounded = result.rounded()
if (result == rounded) {
summaryLbl.text = String(result).replacingOccurrences(of: ".0", with: "", options: .literal, range: nil)
} else {
summaryLbl.text = String(result)
}
} else if sender.tag == 10 {
summaryLbl.text = "0"
previousNumber = 0
actualNumber = 0
operation = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
summaryLbl.text = "0"
previousNumber = 0
actualNumber = 0
operation = 0
}
}
这是简单的计算器。 我的计算有问题。
有人知道如何解决上述问题吗?
答案 0 :(得分:1)
计算器是有限状态机。它可能非常复杂,但最简单的形式类似于:
因此,如果我们保持简单,将上述机器作为目标,则在2 + 5之后,我们的机器期望equals(=)来计算结果,或者如果添加了运算符(例如*),则期望下一位。给运算符(在我们的例子中为负)将导致错误。
复杂度仅受您的想象力限制。您可以添加对小数点数字,方括号,幂等的支持。要添加的糖越多,FSM越复杂。
我建议从最简单的一个开始。保持状态,下一步允许进行转换,并在错误转换的情况下进行错误处理。
迅速在github上查看此存储库以查找有限状态机:https://github.com/vishalvshekkar/SwiftFSM
以及相应的文章: https://blog.vishalvshekkar.com/finite-state-machine-in-swift-ba0958bca34f