在 swift 中乘以变量和双精度数
Multiplying variables and doubles in swift
我是一名正在学习的设计师Swift,我是一名初学者。
我没有任何经验。
我正在尝试使用 Xcode 的 playground 中的基本代码创建一个小费计算器。
这是我目前的情况。
var billBeforeTax = 100
var taxPercentage = 0.12
var tax = billBeforeTax * taxPercentage
我收到错误:
Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
这是否意味着我不能乘双数?
我是否遗漏了变量和双精度的任何基本概念?
同一数据类型只能有两个。
var billBeforeTax = 100 // Interpreted as an Integer
var taxPercentage = 0.12 // Interpreted as a Double
var tax = billBeforeTax * taxPercentage // Integer * Double = error
如果你像这样声明billBeforeTax
..
var billBeforeTax = 100.0
它将被解释为 Double 并且乘法将起作用。或者您也可以执行以下操作。
var billBeforeTax = 100
var taxPercentage = 0.12
var tax = Double(billBeforeTax) * taxPercentage // Convert billBeforeTax to a double before multiplying.
您只需将 int 变量转换为 Double,如下所示:
var billBeforeTax = 100
var taxPercentage = 0.12
var tax = Double(billBeforeTax) * taxPercentage
我是一名正在学习的设计师Swift,我是一名初学者。
我没有任何经验。
我正在尝试使用 Xcode 的 playground 中的基本代码创建一个小费计算器。
这是我目前的情况。
var billBeforeTax = 100
var taxPercentage = 0.12
var tax = billBeforeTax * taxPercentage
我收到错误:
Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
这是否意味着我不能乘双数?
我是否遗漏了变量和双精度的任何基本概念?
同一数据类型只能有两个。
var billBeforeTax = 100 // Interpreted as an Integer
var taxPercentage = 0.12 // Interpreted as a Double
var tax = billBeforeTax * taxPercentage // Integer * Double = error
如果你像这样声明billBeforeTax
..
var billBeforeTax = 100.0
它将被解释为 Double 并且乘法将起作用。或者您也可以执行以下操作。
var billBeforeTax = 100
var taxPercentage = 0.12
var tax = Double(billBeforeTax) * taxPercentage // Convert billBeforeTax to a double before multiplying.
您只需将 int 变量转换为 Double,如下所示:
var billBeforeTax = 100
var taxPercentage = 0.12
var tax = Double(billBeforeTax) * taxPercentage