ada - 使用递归的 Ada 斐波那契数列

标签 ada

在这段代码中,我试图编写一个程序,根据用户的输入(索引、大小)打印出斐波那契数列。然后,程序应该打印出 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/

相关文章:

iphone - 将用 Ada 编写的 Windows/Mac 应用程序移植到 iOS

我可以通过最少的复制从 Unbounded_String 获取 chars_ptr 吗?

recursion - 如何使用递归乘以 N 个 float ?

java - 对于 Crestron/Extron,有 Java Lua D 语言的框架吗?

arrays - 可变 Ada 函数

sockets - 如何在 Ada 中创建 UDP 客户端

interrupt - Ada - pragma Attach_Handler() 是否可以将处理程序附加到 System.Priority'Last 优先级?

cross-compiling - GNAT GPL Ada 在为 Raspberry pi 交叉编译时失败将链接错误

ada - 使用 AVR-Ada 执行任务

Ada 手册 : difference between annotated and consolidated