Menu
Coddy logo textTech

割り勘の計算

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

challenge icon

チャレンジ

簡単

前のレッスンでは、チップの金額と合計金額を計算しました。今回は、最後のステップとして、合計金額を全員で分割する処理を追加しましょう。

チップの金額とチップ込みの合計金額を表示した後、totalpeople の数で割って、各人が支払うべき金額を計算します。

この値を per_person という名前の変数に格納してください。

次に、以下の形式で最終結果を表示します。

Each person pays: $[per_person]

すべての出力には cat() を使用し、必要に応じて改行文字 \n を含めてください。

例えば、入力が 100204 の場合、完全な出力は以下のようになります。

Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $100
Tip: 20%
People: 4
Tip amount: $20
Total with tip: $120
Each person pays: $30

自分で試してみよう

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

基礎のすべてのレッスン