Menu
CoddyTech

计算小费和总额

本课属于 Coddy Ruby 学习旅程的“基础知识”单元。第 36 课,共 88 课。

challenge icon

挑战

简单

在上一课中,你收集了账单金额、小费百分比和人数。现在,添加计算逻辑,计算小费金额和包含小费的账单总额。

显示确认消息后,计算以下内容:

  1. 小费金额:将账单金额乘以小费百分比再除以 100
  2. 账单总额:将原始账单金额与小费金额相加

将它们存储在名为 tip_amount 和 total 的变量中。

然后按以下格式显示计算结果:

Tip amount: $[tip_amount]
Total with tip: $[total]

所有输出都使用 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

亲手试试

# 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

基础知识中的所有课

自己练习: Ruby 在线编译器