Ruby程序打印 Fibonacci 斐波那契系列
Ruby中的斐波那契程序
任务是开发一个程序,以Ruby编程语言打印Fibonacci系列。
在开始构建斐波那契数列的逻辑之前,让我们了解斐波那契数列的确切含义。斐波那契数列不过是一系列数字,其中当前数字是前两个数字的总和。
例如最多10个的斐波那契数列是:1,1,2,3,5,8,13,13,21,34,55
您可以观察到最后一个数字5是2和3的和,其他类似地是前两个数字的和。
您可以借助递归和非递归方法将上述方案放入代码逻辑中。在下面的程序中,提到了两种方法。
使用的方法:
puts:用于通过在控制台上编写文本来与用户进行交互。
gets:此方法用于从用户那里获取字符串形式的输入。
fib():这是用户定义的方法,它遵循递归方法来查找斐波那契数列。
Ruby代码打印斐波那契数列
=begin
Ruby program to print Fibonacci series
without recursion
=end
first=0
second=1
nextterm=0
puts "Enter the number of terms:-"
n=gets.chomp.to_i
puts "The first #{n} terms of Fibonacci series are:-"
c=1
while(c<=n+1)
if(c<=1)
nextterm=c
else
puts nextterm
nextterm=first+second
first=second
second=nextterm
end
c+=1
end输出结果
Enter the number of terms:- 15 The first 15 terms of Fibonacci series are:- 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
方法2:
=begin
Ruby program to print Fibonacci series with recursion
=end
def fib(n)
if (n<=2)
return 1
else
return (fib(n-1)+fib(n-2))
end
end
puts "Enter the number of terms:-"
n=gets.chomp.to_i
puts "The first #{n} terms of fibonnaci series are:-"
for c in 1..n
puts fib(c)end输出结果
Enter the number of terms:- 15 The first 15 terms of fibonnaci series are:- 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610