Menu
Coddy logo textTech

料金の分割

CoddyのSwiftジャーニー「基礎」セクションの一部 — レッスン 40/86。

challenge icon

チャレンジ

簡単

前のレッスンでは、チップの金額とチップを含めた合計金額を計算しました。今回は、割り勘をする際に各人が支払う金額を決定するための最終的な計算を追加しましょう。

すでに計算した totalWithTipnumberOfPeople を使用して、合計を人数で割ることで、各人が支払うべき金額を計算します。

割り算を行う前に、numberOfPeopleInt から 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.0204 の場合、出力は以下のようになります:

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)")
        }
    }
}

基礎のすべてのレッスン