【问题标题】: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 序列。我在这个 while 循环中做错了什么?
【发布时间】:2020-02-22 17:05:45
【问题描述】:

我正在尝试在 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(n)
  • 或在循环外使用print(vector)
  • 您不需要cbind - 只需vector &lt;- c(vector, n) 就可以了。

标签: r while-loop collatz


【解决方案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)

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多