Menu
CoddyTech

請求額を分ける

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

challenge icon

チャレンジ

簡単

前のレッスンでは、チップの金額とチップ込みの合計を計算しました。次に、最後の計算を追加して、請求額を分けるときに各人が支払う金額を求めましょう。

すでに計算した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プレイグラウンド