格式化输出(sprintf)
本课属于 Coddy R 学习旅程的“基础知识”单元。第 37 课,共 78 课。
挑战
简单在上一课中,你完成了账单分摊计算器的所有计算。现在,使用 sprintf() 改进输出格式,让金额显示为恰好 2 位小数。
修改显示金额的输出语句,使用 sprintf() 设置格式。sprintf() 函数可以使用 %.2f 将数字格式化为 2 位小数。
更新以下输出语句,让所有金额都显示为恰好 2 位小数:
Bill: $[bill]Tip amount: $[tip_amount]Total with tip: $[total]Each person pays: $[per_person]
算术运算保持与上一课完全相同:tip_amount <- bill * tip_percent / 100。改为乘以 tip_percent / 100,在结果四舍五入到 2 位小数后,可能会产生 1 分钱的差异。
使用 sprintf() 格式化每个金额。例如,sprintf("%.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注意:小费百分比和人数应保持为整数,不要设置小数格式。
亲手试试
# 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 = "")
# Calculate per person amount
per_person <- total / people
# Display per person amount
cat("Each person pays: $", per_person, "\n", sep = "")基础知识中的所有课
自己练习: R 在线编译器