分摊账单
本课属于 Coddy Ruby 学习旅程的“基础知识”单元。第 37 课,共 88 课。
挑战
简单在上一课中,你计算了小费金额和账单总额。现在,添加最后一步:将总额分摊给所有人。
显示小费金额和含小费的总额后,将 total 除以 people 的人数,计算每个人应该支付多少。
将结果存储在名为 per_person 的变量中。
然后按以下格式显示最终结果:
Each person pays: $[per_person]所有输出都使用 puts,并使用 %g 格式化数字,以避免不必要的末尾零。
例如,如果输入是 100、20 和 4,完整输出应为:
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基础知识中的所有课
自己练习: Ruby 在线编译器