【发布时间】:2021-12-31 17:36:53
【问题描述】:
创建一个运算符类型的子程序,接收两个整数并将它们返回 它们的负和。 IE。如果总和是正数,它将是 结果是否定的,或者总和是否定的结果 积极的。前任。结果 6 和 4 给出 -10,而 2 和 -6 给出 4。
例如:
Type in two integers: **7 -10**
The negative sum of the two integers is 3.
Type in two integers: **-10 7**
The positive sum of the two integers is -3.
子程序中不得输入或打印。
所以我尝试了这个任务,实际上使用一个函数很容易解决它,但是在将它转换为运算符时,我偶然发现了一个问题。
这是我的方法:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Test is
function "+" (Left, Right : in Integer) return Integer is
Sum : Integer;
begin
Sum := -(Left + Right);
return Sum;
end "+";
Left, Right : Integer;
begin
Put("Type in two integers: ");
Get(Left);
Get(Right);
Put("The ");
if -(Left + Right) >= 0 then
Put("negative ");
else
Put("positive ");
end if;
Put("sum of the two integers is: ");
Put(-(Left + Right));
end Test;
我的程序可以编译,但是当我运行它并输入两个整数时,它会显示:
raised STORAGE_ERROR: infinite recursion
如何使用运算符解决这个问题?我设法用过程和函数子程序而不是运算符轻松解决了这个问题。任何帮助表示赞赏!
【问题讨论】:
-
我应该返回布尔值吗?但即便如此,我仍然需要一个 -(Left + Right) 函数,而且我不会那样工作
-
仔细看你用过的算子……
-
我有,在这种情况下你应该用它来添加整数。我将两个输入相加,然后将其转换为负值。
-
尝试使用不同的运算符符号来产生负和。您的解决方案尝试对负和和正和使用“+”符号,从而导致无限递归消息。 Ada 加法运算符是“+”、“-”和“&”。整数没有预定义的“&”用法。