【发布时间】:2020-11-28 05:49:37
【问题描述】:
我正在尝试学习如何实现控制结构,例如 FOR 和 while 循环。
我创建了一个模拟著名巴西乐透投注的函数。 在乐透中,玩家从 1:60 向量(称为 your_bet)中下注 6 个唯一整数。 该函数从 1 到 60 的全域(“结果”)中采样 6 个值,并测试结果中有多少值与 your_bet 匹配,打印出来:
你的赌注
结果
总分(满分 6 分)
对投注结果的三种可能评论之一。
代码如下:
```
LOTTO<-function(your_bet=sample(1:60, size=6, replace=FALSE)){
result<-sample(1:60, size=6, replace=FALSE)
logical_vector<-(your_bet %in% result)
total_points<-sum(as.integer(logical_vector))
print(paste(c("Your bet:", as.character(your_bet))), collapse="")
print(paste(c("Result", as.character(result))), collapse="")
print(paste(c("Total points", as.character(total_points))), collapse="")
if (total_points==6)
print("You are a millonaire")
else if (total_points==5)
print("5 points, you are rich!")
else print("good luck next time")
}
```
然后我尝试实现一个循环,使函数在一个循环中一遍又一遍地循环,直到总点数>=给定目标(此处为 target_points),修改函数如下。
```
LOTTO<-function(your_bet=sample(1:60, size=6, replace=FALSE), stubborn_until_x_points=FALSE,
target_points)#inserted stubborn_until_x_points and target_points arguments{
result<-sample(1:60, size=6, replace=FALSE)
logical_vector<-(your_bet %in% result)
total_points<-sum(as.integer(logical_vector))
print(paste(c("Your bet:", as.character(your_bet))), collapse="")
print(paste(c("Result", as.character(result))), collapse="")
print(paste(c("Total points", as.character(total_points))), collapse="")
if (total_points==6)
print("You are a millonaire")
else if (total_points==5)
print("5 points, you are rich!")
else print("good luck next time")
if (stubborn_until_x_points==TRUE)#Inserted WHILE loop here{
while(total_points < target_points){
LOTTO(your_bet, stubborn_until_x_points=TRUE, target_points)}
}
}
```
这确实使函数在循环中重复,但由于某种原因,即使满足条件,它也会继续循环。
观察 - 我意识到当第一次运行时满足条件时,它实际上会停止,但进入循环后,它会一直持续下去。
我找不到问题所在。有任何想法吗? 提前致谢。
【问题讨论】:
-
看起来你没有更新循环内的 total_points
-
友好的评论。这个函数有一些不必要的递归。将所有代码包含在
while循环中会更有效(并且 C 堆栈安全)。只需从定义total_points <- -Inf和target_points <- Inf开始,然后使用if(stubborn_until_x_points != TRUE)break来测试早期中断。R中的递归限制通常相当严格,因此对于可能达到相当深度的函数,可以删除递归。 -
我该怎么做?可以展示给我吗? @rootkonda
-
如果 target_points 大于 60 那么它也将处于无限循环不是吗?你检查了吗?
标签: r while-loop