计算小费和总额
本课属于 Coddy Swift 学习旅程的“基础知识”单元。第 39 课,共 86 课。
挑战
简单在上一课中,你从用户那里获取了账单总额、小费百分比和人数。现在,添加计算逻辑,计算小费金额以及包含小费的账单总额。
使用你已有的值,计算:
- 小费金额:账单总额乘以小费百分比,再除以 100
- 含小费的总额:账单总额加上小费金额
记得在计算前将小费百分比从 Int 转换为 Double。
更新输出,使其按以下确切格式打印:
Welcome to the Bill Split Calculator!
Bill: [billTotal]
Tip: [tipPercentage]%
People: [numberOfPeople]
Tip amount: [tipAmount]
Total with tip: [totalWithTip]例如,如果输入是 100.0、20 和 4,输出应为:
Welcome to the Bill Split Calculator!
Bill: 100.0
Tip: 20%
People: 4
Tip amount: 20.0
Total with tip: 120.0亲手试试
print("Welcome to the Bill Split Calculator!")
if let billInput = readLine(), let billTotal = Double(billInput) {
if let tipInput = readLine(), let tipPercentage = Int(tipInput) {
if let peopleInput = readLine(), let numberOfPeople = Int(peopleInput) {
print("Bill: \(billTotal)")
print("Tip: \(tipPercentage)%")
print("People: \(numberOfPeople)")
}
}
}基础知识中的所有课
自己练习: Swift 在线编辑器