Put 过程是否改变了我的变量的值?

问题描述 投票:0回答:1

我正在学习 Ada,我编写了一个计算数字阶乘的函数和一个调用它的简单程序。但是,根据我格式化结果显示的方式,我的变量会获得不同的值。

这是我的文件内容:

阶乘.广告
function Factorial (n : in out Natural) return Natural;
阶乘.adb
function Factorial (n : in out Natural) return Natural is
   n_fac : Natural := 0;
begin
   if n = 0 or n = 1 then
      n_fac := 1;
   else
      n_fac := n;
      loop
         n_fac := n_fac * Integer'Pred(n);
         n := n - 1;
         exit when n = 1;
      end loop;
   end if;

   return n_fac;
end Factorial;
show_factorial.adb
with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Factorial;

procedure Show_Factorial is
   A : Natural := 4;
begin
   --  First block
   Put_Line ("-- First block --");
   Put ("Factorial of" & Integer'Image(A) & " is ");
   A := factorial(A);  --  In between Put procedures to save 
   --                       one variable declaration
   Put (                                         A, Width => 0);

   --  Post-execution check
   New_Line;
   Put_Line ("A is" & Integer'Image(A));

   --  Reset variable
   New_Line;
   Put_Line ("-- Var reset --");
   A := 4;
   Put_Line ("A becomes" & Integer'Image(A));
   New_Line;

   --  Second block
   Put_Line ("-- Second block --");
   Put ("Factorial of" & Integer'Image(A) & " is ");
   Put (                               factorial(A), Width => 0);
   A := factorial(A);

   --  Post-execution check
   New_Line;
   Put_Line ("A is" & Integer'Image(A));
end Show_Factorial;

执行上面的程序给出以下输出:

-- First block --
Factorial of 4 is 24
A is 24

-- Var reset --
A becomes 4

-- Second block --
Factorial of 4 is 24
A is 1

由于我的函数 Factorial 的形式参数是一个

in out
参数,我期望它在被调用后会无条件地改变
A
的值,但从终端输出中看到情况并非如此。我希望它至少会变成
4
,因为这是它的初始值,但它以某种方式变成了所有事物的
1

为什么即使我显式地将 Factorial 函数的返回值赋给 A,在第二个块中 A 也会变成 1?

ada
1个回答
0
投票

看起来它来自你的线路:

Put (                               factorial(A), Width => 0);

这会将

A
设置回 1,因为它是一个
in out
参数,并且您不会将结果保存到 A

然后您下一次调用 Factorial:

A := factorial(A);
计算 1 的阶乘,即 1。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.