Swift 提供两大类数字:整数和浮点数。
你可以往数字字面量里插入下划线来提高可读性:1_000_000与1000000完全相同。
浮点字面量可以用十进制或指数记法书写。
let speed: Int = 42 // Explicit Int
let pi: Double = 3.14 // Explicit Double
let giga: Double = 1_000_000_000 // Double with readability underscores
let plancksConstant: Double = 6.62607015e-34 // Double in scientific notation
Swift 提供标准的算术运算符用于数字计算:
| 运算符 | 说明 | 示例 |
|---|---|---|
+ |
加法 |
4 + 6的结果是10
|
- |
减法 |
15 - 10的结果是5
|
* |
乘法 |
2 * 3的结果是6
|
Swift 是类型安全的,不允许在算术运算中混用不同的数字类型。
你不能直接把Int和Double相加或相乘,必须先把其中一个类型转换成与另一个匹配的类型。
/运算符执行除法。
当两个操作数都是整数时,整数除法会截断小数部分:
5.0 / 2.0 // 2.5 (Double division)
5 / 2 // 2 (integer division truncates the remainder)
非零浮点数除以零会得到inf或-inf。
0.0除以0.0会得到nan(非数字)。
相比之下,整数除以零会导致编译时或运行时错误:
print(5.0 / 0.0) // Prints inf
print(-5.0 / 0.0) // Prints -inf
print(0.0 / 0.0) // Prints nan
// The following line will not compile:
// print(5 / 0) // Error: Division by zero
求余运算符(%)用来计算两个整数相除后剩下的余数:
5 % 2 // 1
-5 % 2 // -1
// Dividing by zero produces an error:
// 5 % 0 // Error: Division by zero
在 Swift 中,%是真正的求余运算符,而不是求模运算符。
结果始终取第一个操作数(被除数)的符号,与第二个操作数的符号无关:
5 % -2 // 1
-5 % 2 // -1
你可以用rounded()方法对浮点数取整。
默认情况下,rounded()取最接近的整数。
你也可以指定具体的取整规则,例如.up或.down:
let x = 3.14
let y = x.rounded() // 3.0
let w = x.rounded(.down) // 3.0
let z = x.rounded(.up) // 4.0
声明数字常量或变量时如果不写类型标注,Swift 会推断它的类型:
Int。Double。let x = 42 // Inferred as Int
let y = 42.0 // Inferred as Double
let z: Double = 42 // Explicitly typed as Double
要在不同类型的值之间进行运算,可以用Double(_:)或Int(_:)这样的类型初始化器转换其中一个值:
let integerCount = 42
let floatingCount = Double(integerCount)
print(floatingCount) // Prints 42.0
let pi = 3.14
let integerPi = Int(pi)
print(integerPi) // Prints 3 (fractional part is truncated)
在本练习中,你将编写代码,帮助一位自由职业者与项目经理沟通。 你的任务是提供几个实用函数,用来快速计算日薪和月薪,也可以选择应用给定的折扣。
我们先确定自由职业者和项目经理之间的几条规则:
有时,自由职业者会提出在日薪基础上给出折扣(例如对最忠实的客户或非营利客户)。
折扣用表示百分比的小数来建模,例如25.0(25%)。
实现一个名为dailyRateFrom的函数,根据作为形参传入的时薪计算日薪。
约定规定一天有 8 个计费小时。
dailyRateFrom(hourlyRate: 60)
// Returns 480.0
返回的日薪应该是Double类型。
实现monthlyRateFrom函数,用来计算折扣后的月薪。
它接收两个形参:时薪和以百分比表示的折扣。
monthlyRateFrom(hourlyRate: 77, withDiscount: 10.5)
// Returns 12129
返回的月薪应该向上取整(取上整)到最接近的整数。
实现函数workdaysIn,它接收预算、时薪和折扣,并计算出这些条件可以覆盖多少个完整的工作日。
workdaysIn(budget: 20000, hourlyRate: 80, withDiscount: 11.0)
// Returns 35.0
返回的天数应该向下取整(取下整)到最接近的整数。