分摊账单
本课属于 Coddy R 学习旅程的“基础知识”单元。第 36 课,共 78 课。
挑战
简单在上一课中,你计算了小费金额和账单总额。现在,添加最后一步:把总额分摊给所有人。
显示小费金额和含小费的总额后,用 total 除以 people 的人数,计算每个人应付多少钱。
将结果存储在名为 per_person 的变量中。
然后按以下格式显示最终结果:
Each person pays: $[per_person]使用 cat() 输出所有内容,并在需要的地方加入换行符 \n。
例如,如果输入为 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 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 = "")基础知识中的所有课
自己练习: R 在线编译器