R猜测游戏语法

时间:2017-08-29 16:28:32

标签: r if-statement while-loop

我在制作猜谜游戏时遇到了正确的括号语法问题。这是我的代码的简短示例

number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
input <- 0
rand <- sample(seq(1,100), size = 1)

input = number_result


while(input != rand){

  if(input < rand){
    print("Higher!")
  }
  else if(input > rand){
    print("Lower!")
  }
  else(input = rand){
  return(print("You got it!"))
}
    }

我的错误是:

Error: unexpected '{' in:
"  }
  else(input = rand){"
>     return(print("You got it!"))
[1] "You got it!"
Error: no function to return from, jumping to top level
> }
Error: unexpected '}' in "}"
>     }
Error: unexpected '}' in "    }"
> 

1 个答案:

答案 0 :(得分:-2)

不需要返回,因为您没有定义函数。您还必须指定停止条件!否则你的时间将永远运行。 试试这个

      number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
      input <- 0
      rand <- sample(seq(1,100), size = 1)

      input = number_result
while(input != rand){
  if(input < rand){
    print("Higher!")
  } else if(input > rand){
    print("Lower!")
  } else {
    print("You got it!")
  }
  input <- input + 1
}