Menu
CoddyTech

格式化输出

本课属于 Coddy Swift 学习旅程的“基础知识”单元。第 41 课,共 86 课。

challenge icon

挑战

简单

在上一课中,你计算了每个人要支付的金额。现在,将金额格式化为恰好保留 2 位小数,让输出看起来更精致、专业。

使用 Swift 的 String(format:) 将 tipAmount、totalWithTip 和 amountPerPerson 的值格式化为恰好保留 2 位小数。

格式说明符 "%.2f" 会将 Double 格式化为保留 2 位小数:

let formatted = String(format: "%.2f", someDouble)

更新输出,使其按照以下确切格式打印:

Welcome to the Bill Split Calculator!
Bill: [billTotal]
Tip: [tipPercentage]%
People: [numberOfPeople]
Tip amount: $[tipAmount formatted]
Total with tip: $[totalWithTip formatted]
Each person pays: $[amountPerPerson formatted]

注意,现在每个金额前都加上了 $ 符号,并且所有金额都恰好保留 2 位小数。

例如,如果输入是 85.5、15 和 3,输出应为:

Welcome to the Bill Split Calculator!
Bill: 85.5
Tip: 15%
People: 3
Tip amount: $12.82
Total with tip: $98.33
Each person pays: $32.77

亲手试试

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
            let amountPerPerson = totalWithTip / Double(numberOfPeople)
            
            print("Bill: \(billTotal)")
            print("Tip: \(tipPercentage)%")
            print("People: \(numberOfPeople)")
            print("Tip amount: \(tipAmount)")
            print("Total with tip: \(totalWithTip)")
            print("Each person pays: \(amountPerPerson)")
        }
    }
}

基础知识中的所有课

自己练习: Swift 在线编辑器