Menu
CoddyTech

计算小费和总额

本课属于 Coddy R 学习旅程的“基础知识”单元。第 35 课,共 78 课。

challenge icon

挑战

简单

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

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

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

将这些值存储在名为 tip_amount 和 total 的变量中。

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

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

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

亲手试试

# 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 = "")

基础知识中的所有课

自己练习: R 在线编译器