R语言猜数字游戏

# you will guess a number for 7 times.
# the number is between 1 and 100.


guess_number <- function(){
  choosed_number <- sample(x = 1:100,size = 1,replace = FALSE)
  input <- readline("输入一个数字:")
  input_number <- as.numeric(input)
  i = 1
  while ( i <= 6 ) {
    if (input_number > choosed_number) {
      print(paste("大了,这是第", i, "次"))
      i = i + 1
      input <- readline("再猜一次,输入一个新的数字:")
      input_number <- as.numeric(input)

    }
    if (input_number < choosed_number) {
      print(paste("小了,这是第", i, "次"))
      i = i + 1
      input <- readline("再猜一次,输入一个新的数字:")
      input_number <- as.numeric(input)

    }
    if (input_number == choosed_number) {
      print("猜对了!")
      i = i + 1
      print(paste("你一共猜了", i, "次"))
    }
  }
  print(paste("游戏结束!正确的数字是:", choosed_number))
}

  

猜你喜欢

转载自www.cnblogs.com/dogfaraway/p/12356121.html