繁体   English   中英

我正在尝试在 R 中创建一个带有 while 循环的 Collat​​z 序列。我在这个 while 循环中做错了什么?

[英]I am trying to create a Collatz sequence with while loop in R. What am i doing wrong in this while loop here?

我正在尝试在 R 中创建一个带有 while 循环的 Collat​​z 序列。

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)
}

运行代码后,我得到:

[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

我该怎么做才能只显示最后一行? 我的代码出了什么问题? 感谢您对此的任何帮助。

你有几种方法来处理print(vector)

  • 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循环之外,即
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM