可自定义上限的猜数字游戏_R语言
# you can set the upperlimit number # you will guess a number for log(N) times. guess_number <- function(){ uplimit <- as.numeric(readline("猜数字的下限为1,输入猜数字的上限:")) choosed_number <- sample(x = 1:uplimit,size = 1,replace = FALSE) input <- readline("输入一个数字:") input_number <- as.numeric(input) i = 1 max_times <- ceiling(log(uplimit,base = 2)) while ( i <= max_times ) { 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("猜对了!") print(paste("你一共猜了", i, "次")) break } } print(paste("游戏结束!正确的数字是:", choosed_number)) }