计算时我缺少什么?

时间:2020-04-02 19:56:46

标签: ios swift

我在编程方面还很陌生,但是我目前正在学习iOS。我一直在尝试构建一个计算器,但是有一些问题。例如,当我尝试计算2 + 2时,它显示5。因为当我按第二个数字(在本例中为2)时,它变为3。

有人可以帮助我解决和理解问题吗?

enter image description here

import UIKit

class ViewController: UIViewController {

    var numberOnScreen:Double = 0
    var previousNumber:Double = 0
    var performingMath = false
    var operation = 0


    @IBOutlet weak var label: UILabel!

    @IBAction func numbers(_ sender: UIButton)
    {
        if performingMath == true
        {
            label.text = String(sender.tag)
            numberOnScreen = Double(label.text!)!
            performingMath = false
        }
        else
        {
            label.text = label.text! + String(sender.tag-1)
            numberOnScreen = Double(label.text!)!
        }


    }


    @IBAction func buttons(_ sender: UIButton)
    {

        if label.text != "" && sender.tag != 11 && sender.tag != 16
        {
            previousNumber = Double(label.text!)!

            if sender.tag == 12 {
                label.text = "/"
            }
            else if sender.tag == 13 {
                label.text = "*"
            }
            else if sender.tag == 14 {
                label.text = "-"
            }
            else if sender.tag == 15 {
                label.text = "+"
            }
            operation = sender.tag
            performingMath = true
        }

        else if sender.tag == 16 {
            if operation == 12 {
                label.text = String(numberOnScreen / previousNumber)
            }
            else if operation == 13 {
                label.text = String(numberOnScreen * previousNumber)
            }
            else if operation == 14 {
                label.text = String(numberOnScreen - previousNumber)
            }
            else if operation == 15 {

                label.text = String(numberOnScreen + previousNumber)
            }
        }
        else if sender.tag == 11 {
            label.text = ""
            numberOnScreen = 0
            previousNumber = 0
            operation = 0

        }
    }



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}

0 个答案:

没有答案