Multiplying variables and doubles in swift

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 07:27:13

问题


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 Xcode's playground.

Here is what I have so far.

var billBeforeTax = 100
var taxPercentage = 0.12
var tax = billBeforeTax * taxPercentage

I get the error:

Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'

Does this mean I can't multiply doubles?

Am I missing any of the basic concepts of variables and doubles here?


回答1:


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.



回答2:


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

    var billBeforeTax = 100
    var taxPercentage = 0.12
    var tax = Double(billBeforeTax) * taxPercentage


来源:https://stackoverflow.com/questions/30676752/multiplying-variables-and-doubles-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!