Menu
Coddy logo textTech

書式付き出力 (sprintf)

CoddyのRジャーニー「基礎」セクションの一部。レッスン 37/78。

challenge icon

チャレンジ

簡単

前のレッスンでは、すべての計算を含む Bill Split Calculator を完成させました。ここでは、sprintf() を使用して出力形式を改善し、金額を小数点以下ちょうど 2 桁で表示します。

ドル金額を表示する出力行を変更し、sprintf() を使って書式設定します。sprintf() 関数を使用すると、%.2f を指定して、数値を小数点以下の桁数を指定して書式設定できます。

次の出力行を更新して、すべての金額を小数点以下ちょうど 2 桁で表示してください。

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

算術演算は前のレッスンとまったく同じにしてください: tip_amount <- bill * tip_percent / 100。代わりに tip_percent / 100 を掛けると、数値を小数点以下 2 桁に丸めたときに 1 セントの差が生じる可能性があります。

各金額の書式設定には sprintf() を使用してください。たとえば、sprintf("%.2f", value) は数値を小数点以下 2 桁に書式設定します。

たとえば、入力が 85.50183 の場合、完全な出力は次のようになります。

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

基礎のすべてのレッスン

自分で練習してみよう: Rオンラインコンパイラ