为什么我能这样做:
number *= operand
number += operand
但不是这个(没有得到正确的结果):
number /= operand
number -= operand
8-3给我-5,8/2给我0。如果我做了
number = operand / displayValue
number = operand - displayValue
我得到了正确的答案。
总的来说,我对快速和iOS的开发还很陌生。谢谢你的回答!
这是来自简单计算器的实际代码:
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var isFirstDigit = true
var operand1: Double = 0
var operation = "="
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(label.text!)!.doubleValue
}
set {
label.text = String(format: "%.0f ", newValue)
isFirstDigit = true
operation = "="
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func digit(sender: UIButton) {
let digit = sender.currentTitle!
label.text = isFirstDigit ? digit : label.text! + digit
isFirstDigit = false
}
@IBAction func cancel(sender: AnyObject) {
displayValue = 0
}
@IBAction func calculate(sender: UIButton) {
switch operation {
case "/": displayValue /= operand1
case "*": displayValue *= operand1
case "+": displayValue += operand1
case "-": displayValue -= operand1
default: break
}
}
@IBAction func operations(sender: UIButton) {
operation = sender.currentTitle!
operand1 = displayValue
isFirstDigit = true
}
}
发布于 2015-12-10 04:02:54
我已经在游乐场上试过了,而且它似乎运行得很好。
编辑:
我在XCode上检查了您的代码,并通过更改以下内容解决了这个问题:
// Runs the operations.
switch operation {
case "/": operand1 /= displayValue
case "*": operand1 *= displayValue
case "+": operand1 += displayValue
case "-": operand1 -= displayValue
default: break
}
// Updates the text on the Label.
label.text = "\(operand1)"
似乎您是以相反的顺序执行操作的,这就解释了为什么"+“和"*”工作正常,而不是"/“和"-”。
https://stackoverflow.com/questions/34193317
复制相似问题