【问题标题】:Ada - Operator subprogramAda - 算子子程序
【发布时间】: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 加法运算符是“+”、“-”和“&”。整数没有预定义的“&”用法。

标签: operators ada


【解决方案1】:

您可以使用类型系统来解决这个问题,而无需使用新的运算符符号。

作为提示,运算符可以重载参数和返回类型。仔细阅读该问题会显示指定了输入类型,但未指定输出类型。那么,这个怎么样?

type Not_Integer is new Integer;

function "+" (Left, Right : in Integer) return Not_Integer is 
    Sum : Integer;

begin
    Sum := -(Left + Right);
    return Not_Integer(Sum);
end "+";
   

由于两个“+”运算符的返回类型不同,它们之间没有歧义,也没有无限递归。

您必须修改主程序以将结果分配给Not_Integer 变量才能使用新运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    相关资源
    最近更新 更多