乘以,减去和除以二进制数会给出错误的答案

时间:2017-11-21 06:43:10

标签: swift binary decimal calculator

我正在制作二进制计算器应用程序。 没有构建时间问题,但在应用程序中只添加二进制数给出正确的答案,乘法,减法和除法不会。

  • 划分 - 每个答案= 1(1010-0001 = 1; 10101010-1010 = 1)
  • 乘法 - 每个答案都错了,(11111 x 101010 = 1111000001,应该是10100010110)
  • 减去 - 每个答案= 0(1010-0001 = 0; 1010101-0001 = 0)

我尝试使代码更具说明性,并且它在操场上工作(以print()结尾)但是当我更改应用代码时,答案是相同的。

    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
        {
            label.text = String((decimal + decimal1), radix: 2)
        }
        else if operation == 4 //subtracting
        {
            label.text = String((decimal - decimal1), radix: 2)
        }
        else if operation == 5 //multiplying
        {
            label.text = String((decimal * decimal1), radix: 2)
            }
        else if operation == 7 //dividing
        {
            label.text = String((decimal / decimal1), radix: 2)            
        }

0 个答案:

没有答案