Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我怎样才能得到一个;如有其他",;在r中循环以保存在循环中创建的值,并在循环的未来运行中使用它们?_R_Loops - Fatal编程技术网

我怎样才能得到一个;如有其他",;在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))