-1

使用 Ada (GNAT):我需要确定给定值的 10 次方。最明显的方法是使用对数;但这无法编译。

with Ada.Numerics.Generic_Elementary_Functions;
procedure F(Value : in Float) is
      The_Log : Integer := 0;
begin
      The_Log := Integer(Log(Value, 10));
      G(Value, The_Log);
end;

错误:

  • utility.adb:495:26:“日志”不可见
    • utility.adb:495:26:a-ngelfu.ads:24 的不可见声明,第 482 行的实例
    • utility.adb:495:26:a-ngelfu.ads:23 处的不可见声明,第 482 行的实例

然后我尝试引用包,但这也失败了:

with Ada.Numerics.Generic_Elementary_Functions;
procedure F(Value : in Float) is
      The_Log : Integer := 0;
      package Float_Functions is new Ada.Numerics.Generic_Elementary_Functions (Float);
begin
      The_Log := Integer(Float_Functions.Log(Value, 10));
      G(Value, The_Log);
end;

错误:

  • utility.adb:495:41:没有候选解释与实际相符:
  • utility.adb:495:41:调用“Log”的参数太多
  • utility.adb:495:53:预期类型“Standard.Float”
  • utility.adb:495:53:在 a-ngelfu.ads:24 处对“Log”的调用中找到类型通用整数 ==>,第 482 行的实例
4

2 回答 2

6

我不知道你是否已经修复它,但这是答案。

首先,正如我看到您Float在实例化通用版本时传递的那样,您可以使用非通用版本。

如果您决定使用通用版本,则必须以第二种方式进行,您必须在使用其功能之前实例化包。

查看a-ngelfu.ads您可能会看到所需函数的实际原型(自然对数还有另一个函数,只有 1 个参数):

function Log(X, Base : Float_Type'Base) return Float_Type'Base;

您可以在那里看到基础也需要为浮点类型。通用版本的正确代码是:

with Ada.Numerics.Generic_Elementary_Functions;

procedure F(Value : in Float) is
    -- Instantiate the package:
    package Float_Functions is new Ada.Numerics.Generic_Elementary_Functions (Float);
    -- The logarithm:
    The_Log : Integer := 0;
begin
    The_Log := Integer(Float_Functions.Log(Value, 10.0));
    G(Value, The_Log);
end;

非通用的将完全相同:

with Ada.Numerics.Elementary_Functions;

procedure F(Value : in Float) is
    -- The logarithm:
    The_Log : Integer := 0;
begin
    The_Log := Integer(Ada.Numerics.Elementary_Functions.Log(Value, 10.0));
    G(Value, The_Log);
end;
于 2010-02-10T11:47:41.533 回答
3

桑迪是对的。他的解决方案奏效了。

然而,作为 Ada,有两个例外需要提防……

  • 值 < 0.0
  • 值 = 0.0

如果没有守卫这个函数,因为它会导致生成异常。请记住,返回的 The_Log 可以是 < 0、0 和 > 0。

with Ada.Numerics.Elementary_Functions; 

procedure F(Value : in Float) is 
    -- The logarithm: 
    The_Log : Integer := 0; 
begin 
    if Value /= 0.0 then
        The_Log := Integer(
             Ada.Numerics.Elementary_Functions.Log(abs Value, 10.0)); 
    end if;
    G(Value, The_Log); 
end; 
于 2010-02-11T05:03:17.127 回答