[英]I am trying to create a Collatz sequence with while loop in R. What am i doing wrong in this while loop here?
I am trying to create a Collatz sequence with while loop in R.我正在尝试在 R 中创建一个带有 while 循环的 Collatz 序列。
vector <- NULL
n <- 10
while (n != 1) {
if (n %% 2 == 0) {
n <- n / 2
} else {
n <- (n * 3) + 1
}
vector <- c(vector, cbind(n))
print(vector)
}
After running the code, I got:运行代码后,我得到:
[1] 5
[1] 5 16
[1] 5 16 8
[1] 5 16 8 4
[1] 5 16 8 4 2
[1] 5 16 8 4 2 1
How do I do it such that it only shows the last row?我该怎么做才能只显示最后一行? What went wrong in my code?
我的代码出了什么问题? Thanks for any help on this.
感谢您对此的任何帮助。
You have several ways to deal with print(vector)
你有几种方法来处理
print(vector)
if
condition before print(vector)
, ie,print(vector)
之前添加if
条件,即vector <- NULL
n <- 10
while (n != 1) {
if (n %% 2 == 0) {
n <- n / 2
} else {
n <- (n * 3) + 1
}
vector <- c(vector, cbind(n))
if (n==1) print(vector)
}
while
loop, ie,while
循环之外,即vector <- NULL
n <- 10
while (n != 1) {
if (n %% 2 == 0) {
n <- n / 2
} else {
n <- (n * 3) + 1
}
vector <- c(vector, cbind(n))
}
print(vector)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.