gpt4 book ai didi

swift - 无法使 Swift 中的计算器应用程序获得超过一位数?

转载 作者:行者123 更新时间:2023-11-28 06:09:10 24 4
gpt4 key购买 nike

所以这是我的操作类:

class Calculation {

var currentNumber: String = ""
var resultNumber = Int()
var operationInput = String()


func operationIdentifier() {

if operationInput == "=" {
resultNumber = Int(currentNumber)!
print("\(resultNumber)")
} else if operationInput == "+" {
resultNumber += Int(currentNumber)!
print("\(resultNumber)")
} else if operationInput == "-" {
resultNumber -= Int(currentNumber)!
print("\(resultNumber)")
} else if operationInput == "*" {
resultNumber *= Int(currentNumber)!
print("\(resultNumber)")
} else if operationInput == "/" {
resultNumber /= Int(currentNumber)!
print("\(resultNumber)")
} else {
print("Operation does not exist.")
}

print("\(resultNumber)")
}

这就是我获得此按钮以获取数字标题的地方:

@IBAction func numberPressed(_ sender: UIButton) {

calculation.currentNumber = (sender.titleLabel?.text!)!
calculation.currentNumber.append(<#T##other: String##String#>)
//calculation.currentNumber.append((sender.titleLabel?.text)!) This is how I use it to append.
calculation.operationIdentifier()
resultTextField.text = "\(calculation.currentNumber)"

}

追加命令适用于代码部分所示的字符串,我用它来添加到前一个数字的末尾,结果始终是某个 Int 的两倍,例如:如果你按 5,它返回 55。

最佳答案

首先,您在这里覆盖值:calculation.currentNumber = (sender.titleLabel?.text!)!。其次,您需要在按下后清除当前号码。

这是我给你的概念(你编辑的代码),你可以在 Playground 中尝试。

enum Operator: String {
case plus = "+"
case minus = "-"
case multiply = "*"
case divide = "/"
case equal = "="

}

class Calculation {

var currentNumber: String = ""
var resultNumber = Int()
var operationInput = String()

func recalculate() {
if resultNumber == 0 {
resultNumber = Int(currentNumber) ?? 0
return
}

guard let sign = Operator(rawValue: operationInput), let number = Int(currentNumber) else { return }

switch sign {
case .plus: resultNumber += number
case .minus: resultNumber -= number
case .divide: resultNumber /= number
case .multiply: resultNumber *= number
case .equal: resultNumber = number
}
}

func operatorPressed(_ op: Operator) {
recalculate()
operationInput = op.rawValue
currentNumber = ""

print(resultNumber)
}

func numberPressed(_ number: String) {
currentNumber.append(number)
}
}

let c = Calculation()
c.numberPressed("5")
c.numberPressed("5")
c.operatorPressed(.plus)
c.numberPressed("5")
c.operatorPressed(.multiply)
c.numberPressed("5")
c.operatorPressed(.equal)
c.operatorPressed(.plus)
c.numberPressed("5")
c.operatorPressed(.equal)

关于swift - 无法使 Swift 中的计算器应用程序获得超过一位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com