Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我正在尝试用R中的while循环创建Collatz序列。我在这个while循环中做错了什么?_R_While Loop_Collatz - Fatal编程技术网

我正在尝试用R中的while循环创建Collatz序列。我在这个while循环中做错了什么?

我正在尝试用R中的while循环创建Collatz序列。我在这个while循环中做错了什么?,r,while-loop,collatz,R,While Loop,Collatz,我试图用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) } 如何使其仅显示最后一行?我的代码出了什么问题? 感谢您在这方面的帮助。您有几种方法可以处理

我试图用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)
}
如何使其仅显示最后一行?我的代码出了什么问题?
感谢您在这方面的帮助。

您有几种方法可以处理
打印(矢量)

  • 打印(矢量)
    之前添加
    if
    条件,即

也许您需要
print(n)
或在循环外部使用
print(vector)
您不需要
cbind
-只需
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
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)
}
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)