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

问题描述 投票:3回答:2

因此,我试图独自学习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))
    }
}
r recursion fibonacci
2个回答
0
投票

该代码可以正常工作,但您不应直接将其输入终端。我的建议是:将代码放入脚本文件中(以.R结尾)并获取源代码(使用?source获得帮助,但实际上非常简单)。

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


0
投票

要使其与Rscript一起使用,请替换

nterms = as.integer(readline(prompt="How many terms? "))

with

cat ("How many terms?")
nterms = as.integer (readLines ("stdin", n = 1))

否则,请在具有source ("fib.R")中代码的R Shell中用fib.R执行它>

© www.soinside.com 2019 - 2024. All rights reserved.