首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ada中使用递归的Fibonacci级数

Ada中使用递归的Fibonacci级数
EN

Stack Overflow用户
提问于 2020-11-08 10:15:38
回答 1查看 376关注 0票数 5

在这段代码中,我试图编写一个程序,根据用户的输入(Index,Size)打印出斐波那契数列。然后,程序应该打印出Index..Size之间的所有斐波那契数。我遇到了麻烦,编写了一个递归来计算并打印出斐波那契数。有什么建议吗?

代码语言:javascript
运行
复制
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;

示例:输入Index (斐波那契数列的初始值):1

输入大小(要打印的斐波那契数):5

前5个斐波那契数是:1 1 2 3 5

EN

回答 1

Stack Overflow用户

发布于 2020-11-08 16:53:51

下面是你怎么做的(这段代码是基于https://rosettacode.org/wiki/Fibonacci_sequence#Recursive的)

代码语言:javascript
运行
复制
with Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure Fibonacci is

   First, Amount: Positive;

   function Fib(P: Positive) return Positive is --Recursion
   begin
      if P <= 2 then
         return 1;
      else
         return Fib(P-1) + Fib(P-2);
      end if;
   end Fib;

begin
   Ada.Text_IO.Put_Line("Welcome to the Fibonacci number series!");
   Ada.Text_IO.Put_Line("Enter an initial value and how many Kombinacci numbers you want to print: ");
   Ada.Integer_Text_IO.Get(First);
   Ada.Integer_Text_IO.Get(Amount);
   for I in First .. First + Amount loop
      Ada.Text_IO.Put("Fibonacci(" & Positive'Image(I) & " ) = ");
      Ada.Text_IO.Put_Line(Positive'Image(Fib(I)));
   end loop;
end Fibonacci;
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64734242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档