第二个变量取第一个值

时间:2017-11-21 12:43:45

标签: swift binary decimal calculator

我构建了一个二进制计算器应用程序,对于数字,我有两个变量。 previousNumber和numberOnScreen。我们的想法是将二进制数转换为小数,进行计算并将答案转换回来。

让我们说我选择的第一个(previousNumber)数字是1010,第二个(numberOnScreen)10100

var numberOnScreen:Int = 0;
var previousNumber:Int = 0;
var doingMath = false
var operation = 0;
var decimal = 0;
var decimal1 = 0;
var binary:String = ""
var binary1:String = ""

@IBOutlet weak var label: UILabel!

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

@IBAction func buttons(_ sender: UIButton) {

    if label.text != "" && sender.tag != 6 && sender.tag != 8
    {
        previousNumber = Int(label.text!)!
        binary = "\(previousNumber)"
        decimal = Int(binary, radix: 2)!
        binary1 = "\(numberOnScreen)"
        decimal1 = Int(binary1, radix: 2)!

        operation = sender.tag
        doingMath = true;
    }
    else if sender.tag == 8
    {
        if operation == 3 //adding
        {
            print(previousNumber, numberOnScreen, decimal, decimal1)

打印[1010,10100,10,10}

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

当您点击 = 键时,您需要更新node_modules的计算。将该代码移动到您正在处理的地方 =

decimal1

另外,我建议您删除代码中的幻数并用常量替换它们。对于键标记,您可以定义如下结构:

@IBAction func buttons(_ sender: UIButton) {

    if label.text != "" && sender.tag != 6 && sender.tag != 8
    {
        previousNumber = Int(label.text!)!
        binary = "\(previousNumber)"
        decimal = Int(binary, radix: 2)!

        operation = sender.tag
        doingMath = true;
    }
    else if sender.tag == 8
    {
        binary1 = "\(numberOnScreen)"
        decimal1 = Int(binary1, radix: 2)!

        if operation == 3 //adding
        {
            print(previousNumber, numberOnScreen, decimal, decimal1)

然后您的代码将显示为:

struct Key {
    static let clear = 6
    static let equals = 8
    static let plus = 3
}

更清楚。