在代碼中是一個小問題,我試圖解決但尚未找到解決方案。
此代碼適用於計算器。
它正在做正確的計算。
但是當我按下「清除」按鈕時,在新計算之前仍然是「0」。
例如:我按「清除」和「2」後。屏幕上會出現「02」。
如果有人會查看代碼並查看解決方案,我將不勝感激。斯威夫特計算器。 「0」仍然在屏幕上
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var outputLbl: UILabel!
var btnSound: AVAudioPlayer!
@IBAction func clearBtnPressed(_ sender: Any) {
playSound()
runningNumber = ""
leftValStr = ""
outputLbl.text = ""
currentOperation = Operation.Empty
}
enum Operation: String {
case Divide = "/"
case Multiply = "*"
case Subtract = "-"
case Add = "+"
case Empty = "Empty"
}
var currentOperation = Operation.Empty
var runningNumber = ""
var leftValStr = ""
var rightValStr = ""
var result = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "btn", ofType: "wav")
let soundURL = URL(fileURLWithPath: path!)
do {
try btnSound = AVAudioPlayer(contentsOf: soundURL)
btnSound.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
outputLbl.text = ""
}
@IBAction func numberPressed(sender: UIButton) {
playSound()
runningNumber += "\(sender.tag)"
outputLbl.text = runningNumber
}
@IBAction func onDividePressed(sender: AnyObject) {
processOperation(operation: .Divide)
}
@IBAction func onMultiplyPressed(sender: AnyObject) {
processOperation(operation: .Multiply)
}
@IBAction func onSubtractPressed(sender: AnyObject) {
processOperation(operation: .Subtract)
}
@IBAction func onAddPressed(sender: AnyObject) {
processOperation(operation: .Add)
}
@IBAction func onEqualPressed(sender: AnyObject) {
processOperation(operation: currentOperation)
}
func playSound() {
if btnSound.isPlaying {
btnSound.stop()
}
btnSound.play()
}
func processOperation(operation: Operation) {
playSound()
if currentOperation != Operation.Empty {
if runningNumber != "" {
rightValStr = runningNumber
runningNumber = ""
if currentOperation == Operation.Multiply {
result = "\(Double(leftValStr)! * Double(rightValStr)!)"
} else if currentOperation == Operation.Divide {
result = "\(Double(leftValStr)!/Double(rightValStr)!)"
} else if currentOperation == Operation.Subtract {
result = "\(Double(leftValStr)! - Double(rightValStr)!)"
} else if currentOperation == Operation.Add {
result = "\(Double(leftValStr)! + Double(rightValStr)!)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
}
給你的numberPressed添加一個條件來檢查'if if =='0''替換它否則將它追加到字符串 –
按'clear'後'0'來自哪裏?添加數字時,您處理的是文本而不是數字,因此前導零仍然存在。 – vadian