gpt4 book ai didi

R 中的递归错误(斐波那契数列)

转载 作者:行者123 更新时间:2023-12-03 16:35:06 28 4
gpt4 key购买 nike

所以我正在尝试自己学习 R 并且只是在学习在线教程。我正在尝试编写一个递归函数来打印斐波那契数列的前 n 项,并且无法在没有错误的情况下运行代码:

Error in if (nterms <= 0) { : missing value where TRUE/FALSE needed



我的代码在输入 if else 之前确实要求我输入我认为这也很奇怪。以下是我的代码,任何帮助表示赞赏。
#Define the fibonacci sequence

recurse_fibonacci <- function(n) {
# Define the initial two values of the sequence

if (n <= 1){
return(n)
} else {

# define the rest of the terms of the sequence using recursion
return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
}
}

#Take input from the user
nterms = as.integer(readline(prompt="How many terms? "))

# check to see if the number of terms entered is valid
if(nterms <= 0) {
print("please enter a positive integer")
} else {

# This part actually calculates and displays the first n terms of the sequence
print("Fibonacci Sequence: ")
for(i in 0:(nterms - 1)){
print(recurse_fibonacci(i))
}
}

最佳答案

这是readline的问题在非交互模式下。 readline不等待按键并立即执行下一条指令。下面的解决方案是在this other SO post中发布的解决方案.

我在下面发布了一个完整的答案,对斐波那契数字函数做了一些修改。

recurse_fibonacci <- function(n) {
# Define the initial two values of the sequence
if (n <= 1){
n
} else{
# define the rest of the terms of the sequence using recursion
Recall(n - 1) + Recall(n - 2)
}
}

#Take input from the user
cat("How many terms?\n")
repeat{
nterms <- scan("stdin", what = character(), n = 1)
if(nchar(nterms) > 0) break
}
nterms <- as.integer(nterms)

# check to see if the number of terms entered is valid
if(nterms <= 0) {
print("please enter a positive integer")
} else {
# This part actually calculates and displays the first n terms of the sequence
print("Fibonacci Sequence: ")
for(i in 0:(nterms - 1)){
print(recurse_fibonacci(i))
}
}

这段代码是文件 fib.R的内容.在 Ubuntu 20.04 终端中运行给出
rui@rui:~$ Rscript fib.R
How many terms?
8
Read 1 item
[1] "Fibonacci Sequence: "
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
rui@rui:~$

关于R 中的递归错误(斐波那契数列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62141845/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com