我怎样才能得到一个;如有其他",;在r中循环以保存在循环中创建的值,并在循环的未来运行中使用它们?
我试图运行一个简单的循环来计算我的分数。您可以看到代码非常简单。我想我在这里缺少了一些关于将循环中的值保存到对象的内容。我找到的大多数信息都是关于更复杂的循环的。感觉这应该是一个简单的解决方案,我只是还不明白我怎样才能得到一个;如有其他",;在r中循环以保存在循环中创建的值,并在循环的未来运行中使用它们?,r,loops,R,Loops,我试图运行一个简单的循环来计算我的分数。您可以看到代码非常简单。我想我在这里缺少了一些关于将循环中的值保存到对象的内容。我找到的大多数信息都是关于更复杂的循环的。感觉这应该是一个简单的解决方案,我只是还不明白 test <- function(){ number <- 2 loop <- function(){ entry <- as.numeric(readline(prompt = "Enter Number:"))
test <- function(){
number <- 2
loop <- function(){
entry <- as.numeric(readline(prompt = "Enter Number:"))
if(entry == number){
points <- 2 * points
cat("You have " ,points, " points!", sep ="")
print("Double points!")
}else{
print("Lose a point.")
points <- points - 1
cat("You have " ,points, " points!", sep ="")
if(points > (0)){
loop()
}else{
print("You lose!")
}
}
}
loop()
}
test()
测试您没有为变量点分配任何值。您应该使用点的当前值作为循环
功能的输入。调用loop()
时,如果不是第一次调用,请传入当前值
test <- function() {
number <- 2
starting_points <- 10
loop <- function(points) {
entry <- as.numeric(readline(prompt = "Enter Number:"))
if (entry == number) {
points <- 2 * points
cat("You have " , points, " points!", sep = "")
print("Double points!")
} else{
print("Lose a point.")
points <- points - 1
cat("You have " , points, " points!", sep = "")
if (points > (0)) {
loop(points)
} else{
print("You lose!")
}
}
}
loop(points = starting_points)
}
test()
就这样!谢谢
### Instead of this:
cat("You have " , points, " points!", sep = "")
## use this:
print(paste0("You have " , points, " points!"))
## or this:
print(sprintf("You have %s points", points))