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

apr*_*r92 5 stdin r rscript

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

if (nterms <= 0) { 中的错误:缺少需要 TRUE/FALSE 的值

我的代码在输入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))
    }
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*Jan 0

该代码工作正常,但您不应该按原样将其输入终端。我的建议:将代码放入脚本文件(以 .R 结尾)并获取它的源代码(获取有关它的帮助?source,但实际上非常简单)。

在 R-Studio 中,您只需点击源按钮即可。