gpt4 book ai didi

Swift 2.0 运算符

转载 作者:可可西里 更新时间:2023-11-01 01:02:32 26 4
gpt4 key购买 nike

为什么我可以这样做:

number *= operand
number += operand

但不是这个(没有得到正确的结果):

number /= operand
number -= operand

8 - 3 给我 -5 和 8/2 给我 0。如果我这样做

number = operand / displayValue
number = operand - displayValue

我得到了正确的答案。

总的来说,我是 swift 和 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
}
}

最佳答案

我已经在 Playground 上试过了,它似乎工作得很好。

enter image description here

编辑:

我已经在 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)"

看起来您正在以相反的顺序执行操作,这解释了为什么“+”和“*”可以正常工作但“/”和“-”不能正常工作。

关于Swift 2.0 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193317/

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