書式付き出力 (sprintf)
CoddyのRジャーニー「基礎」セクションの一部 — レッスン 37/78。
チャレンジ
簡単前回のレッスンでは、すべての計算を含む割り勘計算機(Bill Split Calculator)を完成させました。今回は、sprintf() を使用して出力形式を改善し、通貨の値を小数点以下ちょうど2桁で表示するようにします。
ドル金額を表示する出力行を修正し、sprintf() を使用してフォーマットしてください。sprintf() 関数では、%.2f を使用することで、数値を小数点以下2桁の特定の桁数でフォーマットできます。
以下の出力行を更新して、すべての通貨の値が小数点以下ちょうど2桁で表示されるようにしてください:
Bill: $[bill]Tip amount: $[tip_amount]Total with tip: $[total]Each person pays: $[per_person]
各通貨の値をフォーマットするには sprintf() を使用します。例えば、sprintf("%.2f", value) は数値を小数点以下2桁にフォーマットします。
例えば、入力が 85.50、18、3 の場合、完全な出力は以下のようになります:
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注意:チップのパーセンテージと人数は、小数点フォーマットを適用せず、整数のままにしてください。
自分で試してみよう
# 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 = "")