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 haben Sie den Bill Split Calculator mit allen Berechnungen fertiggestellt. Verbessern Sie nun die Formatierung der Ausgabe mit sprintf(), um Geldwerte mit genau 2 Dezimalstellen anzuzeigen.

Ändern Sie die Ausgabezeilen, die Dollarbeträge anzeigen, um sprintf() für die Formatierung zu verwenden. Die Funktion sprintf() ermöglicht es Ihnen, Zahlen mit einer bestimmten Anzahl von Dezimalstellen zu formatieren, wobei %.2f für 2 Dezimalstellen steht.

Aktualisieren Sie die folgenden Ausgabezeilen, um genau 2 Dezimalstellen für alle Geldwerte anzuzeigen:

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

Verwenden Sie sprintf(), um jeden Geldwert zu formatieren. Zum Beispiel formatiert sprintf("%.2f", value) eine Zahl auf 2 Dezimalstellen.

Wenn die Eingaben beispielsweise 85.50, 18 und 3 sind, 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 Trinkgeld-Prozentsatz 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