R 程序打印斐波那契数列


2023年3月2日, Learn eTutorial
4860

什么是斐波那契数列

斐波那契数列是一个数字序列,从 0, 1, 1, 2, 3 等等开始。在斐波那契数列中,我们手动将前两个数字设为 0 和 1。斐波那契数列的其余部分通过计算前两个数字的和来获得,例如斐波那契数列的第三个数字将是 0+1=1,以此类推。

因此,通常我们可以定义斐波那契数列的第 n 项将使用 (n-1) 项和 (n-2) 项之和的公式计算。

fibonacci series

斐波那契数列如何在 R 程序中实现

在这个 R 程序中,在接受用户输入后,我们手动打印数字 0 和 1,然后在 while 循环中通过添加 (n-1) 和 (n-2) 项来找到第 n 项,并更新数字并将计数增加 1。

了解更多关于如何使用递归函数打印斐波那契数列

算法

步骤 1:向用户显示适当的消息

步骤 2:使用 readline() 将用户输入存入变量 total_terms

步骤 3:首先设置 num1=0num2=1

步骤 4:检查变量 total_terms 是否有效,如果无效则重新输入值

步骤 5: 如果(total_terms >2),我们使用 while 循环来查找下一项

步骤 6: while 循环中,我们首先打印两项 num1num2

步骤 7: 通过添加最后两项并打印来计算下一项 nxt

步骤 8:将 num1num2 的值更新为最后两项

步骤 9:继续直到项数达到 total_terms

R 源代码

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

num1 = 0 # first number
num2 = 1 # second number
count = 2
# check if the total_terms  is valid
if (total_terms  <= 0) {
    print("Please enter a positive integer")
} else {
    if (total_terms == 1) {
        print("Fibonacci sequence:")
        print(num1)
    } else {
        print("Fibonacci sequence:")
        print(num1)
        print(num2)
        while (count < total_terms  ) {
            nxt = num1 + num2
            print(nxt)
            # update values
            num1 = num2
            num2 = nxt
            count = count + 1
        }
    }
}
                                      

输出

How many terms? 10
[1] "Fibonacci sequence:"
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
[1] 21
[1] 34