How to execute multiplications and/or divisions in the right order?

后端 未结 5 1704
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 21:11

I am doing a simple calculator, but when performing the multiplication and division, my code doesn\'t make them a priority over plus and minus. When doing -> 2 + 2 * 4, res

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 21:35

    First you have to search in the array to see if there is a ÷ or × sign.

    Than you can just sum or subtract.

    mutating func calculateTotal() -> Double {
      var total: Double = 0
      for (i, stringNumber) in stringNumbers.enumerated() {
        if let number = Double(stringNumber) {
          switch operators[i] {
          case "÷":
            total /= number
          case "×":
            total *= number
          default:
            break
          }
          //Remove the number from the array and make another for loop with the sum and subtract operations.
    
        }
      }
      clear()
      return total
    }
    

    This will work if you are not using complex numbers.

提交回复
热议问题