Swift中的基础数学

Swift中的基础数学,swift,Swift,我对Xcode非常陌生,我正在尝试制作一个简单的应用程序来计算毛利润 我试图使用以下代码,但它返回值“0” 你知道为什么吗 // Playground - noun: a place where people can play import UIKit var costPrice = 10 var salePrice = 100 var grossProfit = ((salePrice - costPrice) / salePrice) * 100 println(grossProf

我对Xcode非常陌生,我正在尝试制作一个简单的应用程序来计算毛利润

我试图使用以下代码,但它返回值“0”

你知道为什么吗

// Playground - noun: a place where people can play

import UIKit

var costPrice = 10

var salePrice = 100

var grossProfit = ((salePrice - costPrice) / salePrice) * 100

println(grossProfit)

10
100
是整数,因此
costPrice
salePrice
是整数。如您所见,整数除法截断。你想在这里使用
10.0
100.0

苹果公司免费出版的iBook“Swift简介”的前几页解释了这一点

Swift是类型安全的,将根据上下文推断类型

var costPrice=10
推断变量
costPrice
是一个整数

这样就不能将整数与其他类型的数字(例如,双精度数字)隐式组合

如果你试试这个

let costPrice = 10.0

let salePrice = 100.0

let grossProfit = ((salePrice - costPrice) / salePrice) * 100.0

您会发现这是可行的。

因为您使用整数文本初始化变量,所以它们会被类型化为整数。因此,后面的除法是整数除法,它向下舍入。您需要使用不同的方法(浮点或十进制类型,将值放大100倍等)。您忘记了为变量添加类型,因此基本上它们只是整数,而不是浮点。