如何仅使用 Ada 中的 Image 功能来控制显示的小数位数?

Asc*_*lar 3 numbers decimal ada display

我在 Ada 中有以下代码行,

     Put_Line ("Array of " & Integer'Image (iterations)
        & "          is " & Long_Float'Image (sum) 
        & " Time = " & Duration'Image(milliS) & timescale);  
Run Code Online (Sandbox Code Playgroud)

sum 中的小数位数太长而无法显示(不适用于计算,因为 sum 计算需要长浮点数)。我知道 Ada 有使用前后显示小数的替代方法,而不使用 Image 函数,但在我切换到替代方法之前,我想知道 Image 是否有选项或其他显示小数的技术。Image 函数有显示小数的选项吗?是否有一种技术可以缩短 Long_Float 的小数位数仅用于显示?

with Ada.Numerics;
 with Ada.Text_IO; use Ada.Text_IO;

 procedure Images is
 sum                : Standard.Long_Float;
 Pi                 : Long_Float := Ada.Numerics.Pi;

  type Fixed is delta 0.001 range -1.0e6 .. 1.0e6;
  type NewFixed is range -(2 ** 31) .. +(2 ** 31 - 1);
  type Fixed2 is new Long_Float range -1.0e99.. 1.0e99;
  type Fixed3 is new Long_Float range -(2.0e99) .. +(2.0e99);


 begin
 sum:=4.99999950000e14;
 Put_Line ("no fixing number: " & Pi'Image);
 Put_Line (" fixed number: " & Fixed'Image(Fixed (Pi)));
 Put_Line ("no fixing number: " & Long_Float'Image(sum));
 Put_Line (" testing fix: " & Fixed3'Image(Fixed3 (sum)));
 end Images;
Run Code Online (Sandbox Code Playgroud)

附录:

  1. 请注意,我的变量 sum 被定义为 Standard.Long_Float 以与整个程序中使用的其他变量一致。
  2. 我正在添加代码来显示我的问题的罪魁祸首以及我解决问题的尝试。它基于 Simon Wright 提供的示例,我添加了总和数。看起来我只需要弄清楚如何将 delta 插入 Fixed3 类型,因为 delta 定义了小数位数。

Sim*_*ght 6

’Image没有任何选项,请参阅ARM2012 3.5(35)(也为(55.4))。

但是,Ada 202x ARM K.2(88)4.10(13)提出了替代方案:

with Ada.Numerics;
with Ada.Text_IO; use Ada.Text_IO;
procedure Images is
   Pi : Long_Float := Ada.Numerics.Pi;
   type Fixed is delta 0.001 range -1.0e6 .. 1.0e6;
begin
   Put_Line (Pi'Image);
   Put_Line (Fixed (Pi)'Image);
end Images;
Run Code Online (Sandbox Code Playgroud)

其中报告(GNAT CE 2020,FSF GCC 10.1.0)

$ ./images 
 3.14159265358979E+00
 3.142
Run Code Online (Sandbox Code Playgroud)


Gne*_*nte 5

Image 属性对于所有类型具有相同的参数,因此无法指定格式。有在Ada.Text_IO通用嵌套包用于处理数字类型的I / O。对于您的情况,您可以为 Float 实例化 Ada.Text_IO.Float_IO 或仅使用内置的Ada.Float_Text_IO实例。然后您可以使用 Put 过程来指定格式。Ada 标准中有一个例子:

    package Real_IO is new Float_IO(Real); use Real_IO;
    -- default format used at instantiation, Default_Exp = 3
    
    X : Real := -123.4567;  --  digits 8      (see 3.5.7)
    
    Put(X);  -- default format                            "–?1.2345670E+02"
    Put(X, Fore => 5, Aft => 3, Exp => 2);                -- "bbb–?1.235E+2"
    Put(X, 5, 3, 0);                                      -- "b–?123.457"

Run Code Online (Sandbox Code Playgroud)