在这段代码中,我试图编写一个程序,根据用户的输入(索引、大小)打印出斐波那契数列。然后,程序应该打印出 Index..Size 之间的所有斐波那契数。我在编写一个计算并打印出斐波那契数列的递归时遇到了麻烦。有什么建议?
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO, Ada.Unchecked_Deallocation;
procedure Fibonacci is
type Arr is array (Positive range <>) of Integer;
type Array_Access is access Arr;
Size, Index : Positive;
Variable : Array_Access;
procedure Free is new Ada.Unchecked_Deallocation (Arr, Array_Access);
procedure Recursion (Item : Arr) is --Recursion
begin
Put_Line
(Item (Item'First)'Image); --Prints out the numbers
Recursion
(Item
(Item'First + Item'First + 1 ..
Item'Last)); --Calculating the Fibonacci numbers
end Recursion;
begin
Put ("Welcome to the Fibonacci number series!");
Put
("Enter an initial value and how many Fibonacci numbers you want to print: ");
Get (Index);
Get (Size);
Variable := new Arr (Index .. Size);
Recursion (Variable);
end Fibonacci;
示例:输入指数(斐波那契数列的初始值):1输入大小(要打印多少斐波那契数):5
前 5 个斐波那契数是: 1 1 2 3 5
最佳答案
来自 Wikipedia ,
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F0 = 0
F1 = 1
and
Fn = Fn - 1 + Fn - 2
这很直接地翻译成
function Fibonacci (N : Natural) return Natural is
(case N is
when 0 => 0,
when 1 => 1,
when others => Fibonacci (N - 1) + Fibonacci (N - 2));
或者,老式,function Fibonacci (N : Natural) return Natural is
begin
if N = 0 then
return 0;
elsif N = 1 then
return 1;
else
return Fibonacci (N - 1) + Fibonacci (N - 2);
end if;
end Fibonacci;
您确实必须在函数之外进行打印,不可否认,重复计算较低结果的效率低下,但您并没有要求效率。
关于ada - 使用递归的 Ada 斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64734242/