1、取整数
向上取整数
ceil(_: Double) -> Double
向下取整数
floor(_: Double) -> Double
四舍五入取整数
round(_: Double) -> Double
直接去掉数字的小数部分
trunc(_: Double) -> Double
let floatNum = 3.1415926
print("ceil = \(ceil(floatNum)), floor = \(floor(floatNum)), round = \(round(floatNum))")
print("trunc\(trunc(-6.534))")
输出:
ceil = 4.0, floor = 3.0, round = 3.0
trunc = 6.0
2、求绝对值
浮点数求绝对值
fabs(_: Double) -> Double
整数求绝对值
func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric
此函数可以根据T的类型,求对应的绝对值
let oneNum = -3.14
let oneInt = -4
print("fabs = \(fabs(oneNum)) abs = \(abs(oneInt))")
输出:fabs = 3.14 abs = 4
3、指数与对数
求取自然数e的幂
exp(_ x: Double) -> Double
开平方
sqrt(_: Double) -> Double
求以e为底的对数
log(_ x: Double) -> Double
求以2为底的对数
log2(_ x: Double) -> Double
求以10为底的对数
log10(_ x: Double) -> Double
计算以x为底数的y次幂
pow(_: Double, _: Double) -> Double
let twoNum = 2.0
print("exp = \(exp(twoNum)), sqrt = \(sqrt(twoNum))\n log = \(log(twoNum)), log2 = \(log2(twoNum)), log10 = \(log10(twoNum)) \npow = \(pow(twoNum, 3))")
输出:
exp = 7.38905609893065, sqrt = 1.4142135623730951
log = 0.6931471805599453 log2 = 1.0 log10 = 0.3010299956639812
pow = 8.0