打印 斐波那契数列_Ruby程序打印Fibonacci系列

打印 斐波那契数列

Ruby中的斐波那契程序 (Fibonacci program in Ruby)

The task is to develop a program that prints Fibonacci series in Ruby Programming Language.

任务是开发一个程序, 以Ruby编程语言打印Fibonacci系列

Before getting into the logic to build Fibonacci series, let us understand what exactly a Fibonacci series means. Fibonacci series is nothing but a series of numbers in which the current number is the sum of the previous two numbers.

在开始构建斐波那契数列的逻辑之前,让我们了解斐波那契数列的确切含义。 斐波那契数列不过是一系列数字,其中当前数字是前两个数字的总和。

e.g. The Fibonacci series up to 10 is: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

例如最多10个的斐波那契数列是:1、1、2、3、5、8、13、21、34、55

You can observe that the last number 5 is the sum of 2 and 3 and others are similarly the sum of the previous two numbers.

您可以观察到最后一个数字5是2和3的和,其他类似地是前两个数字的和。

You can put the above scenario in the code logic with the help of recursive as well as non-recursive approach. In the following program, both methods are mentioned.

您可以借助递归和非递归方法将上述方案放入代码逻辑中。 在下面的程序中,提到了两种方法。

Methods used:

使用的方法:

  • puts: Used to create an interaction with the user by writing texts on the console.

    puts :用于通过在控制台上编写文本来与用户进行交互。

  • gets: This method is used to take input from the user in the form of string.

    gets :此方法用于从用户那里获取字符串形式的输入。

  • fib(): This is a user-defined method which is following the recursive approach of finding the Fibonacci series.

    fib() :这是用户定义的方法,它遵循递归方法来查找斐波那契数列。

Ruby代码打印斐波那契数列 (Ruby code to print a Fibonacci series)

=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

Output

输出量

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

Method 2:

方法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

Output

输出量

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


翻译自: https://www.includehelp.com/ruby/print-fibonacci-series.aspx

打印 斐波那契数列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值