格式化输出
本课属于 Coddy Ruby 学习旅程的“基础知识”单元。第 38 课,共 88 课。
挑战
简单在上一课中,你完成了账单分摊计算器的所有计算。现在,使用 Ruby 的字符串格式化功能改进输出格式,让金额恰好显示 2 位小数。
修改显示金额的输出行,使用带有 % 运算符的格式字符串。Ruby 可以使用 %.2f 将数字格式化为指定的小数位数,其中 %.2f 表示保留 2 位小数。
更新以下输出行,让所有金额恰好显示 2 位小数:
Bill: $[bill]Tip amount: $[tip_amount]Total with tip: $[total]Each person pays: $[per_person]
使用 % 运算符格式化每个金额。例如,"%.2f" % value 会将数字格式化为保留 2 位小数。
例如,如果输入是 85.50、18 和 3,完整输出应为:
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注意:小费百分比和人数应保持为整数,不要进行小数格式化(使用 %g 避免末尾出现多余的零)。
亲手试试
# 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
# Calculate per person amount
per_person = total / people
# Display per person amount
puts "Each person pays: $%g" % per_person基础知识中的所有课
自己练习: Ruby 在线编译器