2013-12-18 21 views
0

我有一个Ada程序来计算从文件中取得的200个值的平均值和标准差,并且它们都能正常工作。这些包是浮动类型,如何将它们变成泛型?如何在Ada中打包一个通用包?

平均包广告的文件是:

with Text_IO; 
package avg is 
    type int_array is Array (1..200) of integer; 
    function avrage (ParArray: int_array) return float; 
end avg; 

,平均包体:

with Text_IO; 
WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO; 
package body avg is 
function avrage (ParArray: int_array) return float is 
    result: float :=0.0; 
    final:float :=0.0; 
    myarray: int_array:=ParArray; 
begin 
    for v in myarray'Range loop 
    result:= result + float(myarray(v)); 
    end loop; 
    final:=result/200.0; 
    return final; 
end avrage; 
end avg; 

我用“与”和“使用”调用这个包在我的主程序。请告诉我该怎么办

+0

你为什么'用with上Text_Io;'当你不指任何在'Text_IO'中声明的东西? –

+0

为什么你使用'avg'和'avrage'?为什么不使用'Average'和'Mean'(或者'Statistics'和'Mean')?为什么你将'ParArray'复制到'myarray'? –

+0

,因为我被告知我无法修改参数数组,所以我刚刚在函数中创建了一个本地数组,并使其返回本地数组。 @SimonWright –

回答

1

你不说你想要你的包是通用的

我假定要输入到某种类型Input_Value通过Input_Index索引的阵列(下面Input_Values),并且希望的输出是一些浮点类型Result_Value的。您需要功能To_Result_ValueInput_Value转换为Result_Value

generic 
    type Input_Value is private; 
    type Input_Index is (<>); 
    type Input_Values is array (Input_Index range <>) of Input_Value; 
    type Result_Value is digits <>; 
    with function To_Result_Value (X : Input_Value) return Result_Value; 
package Statistics is 
    function Mean (Input : Input_Values) return Result_Value; 
end Statistics; 

...与执行:

package body Statistics is 
    function Mean (Input : Input_Values) return Result_Value is 
     Sum : Result_Value := 0.0; 
    begin 
     for I of Input loop 
     Sum := Sum + To_Result_Value (I); 
     end loop; 
     return Sum/Result_Value (Input’Length); 
    end Mean; 
end Statistics; 

... ...还有一点演示:

with Ada.Text_IO; 
with Statistics; 
procedure Demo is 
    type Arr is array (Integer range <>) of Integer; 
    function To_Float (X : Integer) return Float is 
    begin 
     return Float (X); 
    end To_Float; 
    package Avg is new Statistics (Input_Value => Integer, 
            Input_Index => Integer, 
            Input_Values => Arr, 
            Result_Value => Float, 
            To_Result_Value => To_Float); 
    A : Arr := (1, 2, 3, 4, 5); 
    M : Float; 
begin 
    M := Avg.Mean (A); 
    Ada.Text_IO.Put_Line ("mean is " & Float'Image (M)); 
end Demo; 
+0

非常感谢,你做的是完美的。你知道有关ADA的优秀教科书吗? –

+0

这是不够通用,我需要能够插入一个浮点数/整数,并能够获得输出中的浮点数/整数。我尝试过更改To_Float函数和程序包初始化,但是我得到一个错误,表示期望在您创建Result_Vlaue类型数字的“Result_Value”的实例化中使用的浮点类型,我可以将它设为Private吗? –

+0

你可以使Result_Value为private,但是你必须为''+“',''/”',总和的初始值(零)添加通用参数, '整数'到'Result_Value'(转换'Input'Length')。而且,如果'Result_Value'是一个整数类型,我认为当除以输入数组的长度时,你会遇到四舍五入/截断的问题吗?你总是可以产生一个浮点结果,并让调用者将其转换为所需的类型,这将使​​他们有更多的控制权。见[this](https://www.dropbox.com/s/wn2579wrqxun1l0/statistics.ada)。 –