Multiplying variables and doubles in swift

前端 未结 2 1712
暖寄归人
暖寄归人 2020-12-16 13:52

I\'m a designer looking into learning Swift and I\'m a beginner.

I have no experience whatsoever.

I\'m trying to create a tip calculator using basic code in

相关标签:
2条回答
  • 2020-12-16 14:33

    You can only multiple two of the same data type.

    var billBeforeTax = 100 // Interpreted as an Integer
    var taxPercentage = 0.12 // Interpreted as a Double
    var tax = billBeforeTax * taxPercentage // Integer * Double = error
    

    If you declare billBeforeTax like so..

    var billBeforeTax = 100.0
    

    It will be interpreted as a Double and the multiplication will work. Or you could also do the following.

    var billBeforeTax = 100
    var taxPercentage = 0.12
    var tax = Double(billBeforeTax) * taxPercentage // Convert billBeforeTax to a double before multiplying.
    
    0 讨论(0)
  • 2020-12-16 14:34

    You just have to cast your int variable to Double as below:

        var billBeforeTax = 100
        var taxPercentage = 0.12
        var tax = Double(billBeforeTax) * taxPercentage
    
    0 讨论(0)
提交回复
热议问题