出力の整形
CoddyのSwiftジャーニー「基礎」セクションの一部。レッスン 41/86。
チャレンジ
簡単前のレッスンでは、各人が支払う金額を計算しました。次に、金額を小数点以下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プレイグラウンド