Menu
CoddyTech

回顾:年龄计算器

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

challenge icon

挑战

简单

编写一个简单的年龄计算器,读取出生年份和当前年份,然后计算并显示这个人的年龄。

你会收到两个输入:

  1. 出生年份
  2. 当前年份

起始代码使用 readLines() 读取这两个输入(readline() 只在交互式会话中有效,所以这里无法读取任何内容)。使用 as.numeric() 将它们转换为数值,然后用当前年份减去出生年份来计算年龄。

按以下格式显示输出:

You are [age] years old

使用 cat() 输出,并在末尾添加换行符 \n。

例如,如果输入是 1995 和 2024,输出应为:

You are 29 years old

亲手试试

# 读取输入
con <- file("stdin", "r")
birth_year <- suppressWarnings(readLines(con, n = 1))
current_year <- suppressWarnings(readLines(con, n = 1))

# TODO:将输入转换为数值并计算年龄


# 按以下格式输出结果:"You are [age] years old"
cat("You are", age, "years old\n")

基础知识中的所有课

自己练习: R 在线编译器