Menu
CoddyTech

使用 sprintf() 格式化字符串

本课属于 Coddy R 学习旅程的“逻辑与流程”单元。第 2 课,共 64 课。

sprintf() 会根据模板构建字符串。每个 % 占位符都会被下一个参数替换:%s 用于文本,%d 用于整数,%f 用于小数。

name <- "Ada"
age <- 36
print(sprintf("%s is %d years old", name, age))

输出:

[1] "Ada is 36 years old"

%d 只接受整数:sprintf("%d", 2.5) 会因错误而停止。

% 和 f 之间的精度用于设置小数位数,因此 %.2f 会四舍五入到小数点后两位:

total <- 3 * 4.5 * 1.2
print(sprintf("Total: %.2f", total))

输出:

[1] "Total: 16.20"

宽度会将值填充到指定的字符数:%5d 在左侧填充,%-6s 在右侧填充,%03d 则用零填充。%% 会打印百分号。

print(sprintf("[%5d]", 42))
print(sprintf("[%-6s]", "tea"))
print(sprintf("%03d", 7))
print(sprintf("%d%%", 85))

输出:

[1] "[   42]"
[1] "[tea   ]"
[1] "007"
[1] "85%"

sprintf() 是向量化的:使用向量参数时,它会为每个元素返回一个字符串。cat() 配合 sep = "\n" 使用时,会将每个字符串打印在单独一行。

items <- c("tea", "cake")
prices <- c(4, 12.5)
lines <- sprintf("%-5s %6.2f", items, prices)
cat(lines, sep = "\n")

输出:

tea     4.00
cake   12.50
challenge icon

挑战

简单

完成 receipt_line(item, qty, price)。返回商品、数量和行总额(qty * price),格式为 tea x3 = 13.50:商品、一个空格、x 后面跟着数量,然后是 = 和保留两位小数的总额。

提供的代码会读取商品、数量和价格(每行一个),并打印返回的值。

亲手试试

receipt_line <- function(item, qty, price) {
  # 在这里编写你的代码
  ""
}

# 提供的输入和输出代码:保持原样
input <- suppressWarnings(readLines(file("stdin")))
cat(receipt_line(input[1], as.integer(input[2]), as.numeric(input[3])), sep = "\n")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: R 在线编译器