Menu
Coddy logo textTech

割り勘の計算

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

challenge icon

チャレンジ

簡単

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

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

これを per_person という名前の変数に保存してください。

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

Each person pays: $[per_person]

すべての出力に puts を使用し、不要な末尾のゼロを避けるために %g を使って数値をフォーマットしてください。

例えば、入力が 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 puts to display the welcome message
puts "Welcome to the Bill Split Calculator!\nLet's split your bill fairly."

# Read user inputs
bill = gets.chomp.to_f
tip_percent = gets.chomp.to_f
people = gets.chomp.to_f

# Display confirmation message
puts "Bill: $%g" % bill
puts "Tip: %g%%" % tip_percent
puts "People: %g" % people

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

# Display calculation results
puts "Tip amount: $%g" % tip_amount
puts "Total with tip: $%g" % total

基礎のすべてのレッスン