Menu
Coddy logo textTech

Die Rechnung teilen

Teil des Abschnitts Grundlagen der Swift-Journey von Coddy — Lektion 40 von 86.

challenge icon

Aufgabe

Einfach

In der vorherigen Lektion haben Sie den Trinkgeldbetrag und den Gesamtbetrag inklusive Trinkgeld berechnet. Fügen Sie nun die letzte Berechnung hinzu, um zu bestimmen, wie viel jede Person zahlt, wenn die Rechnung geteilt wird.

Verwenden Sie den bereits berechneten totalWithTip und die numberOfPeople, um den Betrag zu berechnen, den jede Person zahlen sollte, indem Sie den Gesamtbetrag durch die Anzahl der Personen teilen.

Denken Sie daran, numberOfPeople von Int in Double umzuwandeln, bevor Sie die Division durchführen.

Aktualisieren Sie Ihre Ausgabe, um sie in genau diesem Format auszugeben:

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

Wenn die Eingaben beispielsweise 100.0, 20 und 4 sind, sollte die Ausgabe wie folgt aussehen:

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

Probier es selbst

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

Alle Lektionen in Grundlagen