Menu
Coddy logo textTech

Formatierte Ausgabe (sprintf)

Teil des Abschnitts Grundlagen der R-Journey von Coddy. Lektion 37 von 78.

challenge icon

Aufgabe

Einfach

In der vorherigen Lektion hast du den Bill Split Calculator mit allen Berechnungen fertiggestellt. Verbessere nun die Ausgabeformatierung mithilfe von sprintf(), um Geldbeträge mit genau 2 Nachkommastellen anzuzeigen.

Ändere die Ausgabezeilen, die Dollarbeträge anzeigen, sodass sie sprintf() zur Formatierung verwenden. Mit der Funktion sprintf() kannst du Zahlen mit einer bestimmten Anzahl von Nachkommastellen formatieren, indem du %.2f für 2 Nachkommastellen verwendest.

Aktualisiere die folgenden Ausgabezeilen, damit alle Geldbeträge genau 2 Nachkommastellen anzeigen:

  • Bill: $[bill]
  • Tip amount: $[tip_amount]
  • Total with tip: $[total]
  • Each person pays: $[per_person]

Behalte die Arithmetik genau wie in der vorherigen Lektion bei: tip_amount <- bill * tip_percent / 100. Eine Multiplikation mit tip_percent / 100 stattdessen kann zu einem Unterschied von einem Cent führen, sobald die Zahl auf zwei Nachkommastellen gerundet wird.

Verwende sprintf(), um jeden Geldbetrag zu formatieren. Zum Beispiel formatiert sprintf("%.2f", value) eine Zahl auf 2 Nachkommastellen.

Wenn die Eingaben beispielsweise 85.50, 18 und 3 lauten, sollte die vollständige Ausgabe wie folgt aussehen:

Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $85.50
Tip: 18%
People: 3
Tip amount: $15.39
Total with tip: $100.89
Each person pays: $33.63

Hinweis: Der Trinkgeldprozentsatz und die Anzahl der Personen sollten als ganze Zahlen ohne Dezimalformatierung beibehalten werden.

Probier es selbst

# TODO: Write your code below
# Use cat() to display the welcome message
# Remember to use \n for new lines
cat("Welcome to the Bill Split Calculator!\nLet's split your bill fairly.\n")

# Read user inputs
con <- file("stdin", "r")
bill <- as.numeric(suppressWarnings(readLines(con, n = 1)))
tip_percent <- as.numeric(suppressWarnings(readLines(con, n = 1)))
people <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)

# Display confirmation message
cat("Bill: $", bill, "\n", sep = "")
cat("Tip: ", tip_percent, "%\n", sep = "")
cat("People: ", people, "\n", sep = "")

# Calculate tip amount and total
tip_amount <- bill * tip_percent / 100
total <- bill + tip_amount

# Display calculation results
cat("Tip amount: $", tip_amount, "\n", sep = "")
cat("Total with tip: $", total, "\n", sep = "")

# Calculate per person amount
per_person <- total / people

# Display per person amount
cat("Each person pays: $", per_person, "\n", sep = "")

Alle Lektionen in Grundlagen

Übe selbstständig: Online-R-Compiler