分摊账单
本课属于 Coddy Swift 学习旅程的“基础知识”单元。第 40 课,共 86 课。
挑战
简单在上一课中,你计算了小费金额和加上小费后的总金额。现在,添加最后一步计算,确定分摊账单时每个人需要支付多少。
使用你已经计算出的 totalWithTip 和 numberOfPeople,用总金额除以人数,计算每个人应支付的金额。
记得在进行除法之前,将 numberOfPeople 从 Int 转换为 Double。
更新输出,使其按以下确切格式打印:
Welcome to the Bill Split Calculator!
Bill: [billTotal]
Tip: [tipPercentage]%
People: [numberOfPeople]
Tip amount: [tipAmount]
Total with tip: [totalWithTip]
Each person pays: [amountPerPerson]例如,如果输入是 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
Each person pays: 30.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) {
let tipAmount = billTotal * Double(tipPercentage) / 100
let totalWithTip = billTotal + tipAmount
print("Bill: \(billTotal)")
print("Tip: \(tipPercentage)%")
print("People: \(numberOfPeople)")
print("Tip amount: \(tipAmount)")
print("Total with tip: \(totalWithTip)")
}
}
}基础知识中的所有课
自己练习: Swift 在线编辑器