料金の分割
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)")
}
}
}