r - 我的 R 函数的奇怪输出
问题描述
我写的 R 函数有一个小问题。我编写了一个小游戏,你必须猜一个数字。游戏会告诉您您的猜测是高于还是低于您必须猜测的数字。如果您猜对了数字,则游戏结束。
现在我不明白的是:当我开始游戏并在第一次迭代时输入正确的数字时,一切都很好。但是,例如,当我在第一次迭代中输入一个字符(这将被第一个 if 子句捕获)然后在第二次迭代(或任何其他迭代)中输入正确的数字时,我收到了自己的错误消息,“发生了未知错误”,以及来自 R 本身的警告说“猜测(x):强制引入的 NA”。
显然我的程序无法定义用户给出的数字是否等于生成的数字。至少不是在除第一次之外的每一次迭代中。但为什么?
关于输入高于或低于生成的数字的 if 子句按预期工作。
我希望有人可以帮助我/解释我做错了什么:) 提前致谢!
这是代码:
guess <- function(rng) {
cat("Which number are we looking for?", "\n")
a <- readline()
# print(a)
if (is.na(as.numeric(a))) {
cat("Please enter a number!", "\n")
guess(rng)
}
a <- as.numeric(a)
# cat("rng is", rng)
if (a == rng) {
return("Congratulations! You guessed right - 100 points for you!")
}
if (a < rng) {
cat("The number we are looking for is greater than your guessed number!", "\n")
guess(rng)
}
if (a > rng) {
cat("The number we are looking for is lower than you guessed number!", "\n")
guess(rng)
}
stop("Unknown error occured!")
}
guessTheNumber <- function(lower_border=1, upper_border=5) {
x <- as.numeric(sample(lower_border:upper_border, 1))
cat("The number we are looking for is", x, ".", "\n") # for testing purposes
guess(x)
}
解决方案
如果你会使用 if -- else if -- else,那么它会工作得很好
guess <- function(rng) {
cat("Which number are we looking for?", "\n")
a <- readline()
# print(a)
if (is.na(as.numeric(a))) {
cat("Please enter a number!", "\n")
guess(rng)
} else{
a <- as.numeric(a)
# cat("rng is", rng)
if (a == rng) {
return("Congratulations! You guessed right - 100 points for you!")
} else if (a < rng) {
cat("The number we are looking for is greater than your guessed number!", "\n")
guess(rng)
} else if (a > rng) {
cat("The number we are looking for is lower than you guessed number!", "\n")
guess(rng)
} else stop("Unknown error occured!")
}
}
推荐阅读
- php - CodeIgniter:在树枝中打印映射对象
- css - CSS ::首字母伪元素
- python - Python 3.x:将字典值转换为列表
- r - 带有 R 的 JAGS:模拟数据并一次拟合多个模型
- html - 引导程序 4 是否阻止显示背景图像?
- c# - 如何知道模型或 ActionExecutingContext 参数是否是实体(asp.net core 5)
- python - 是否可以将默认参数传递给 for 循环?
- c# - 在 wpf 应用程序的命名空间“System.Drawing”中找不到类型“Icon”
- sql - ORACLE APEX 使用 LEFT JOIN 删除行
- node.js - Oauth/Zoom API 发布请求 - Mocha 集成测试失败,出现 400(客户端错误),而应用程序本身似乎可以工作