Ada:Float/Fixed 的小数部分作为整数
Ada: Fraction part of Float/Fixed as Integer
在 Ada 中,我想将 12.345 这样的数字分成两个不同的整数:
whole : integer := 12;
fraction : integer := 345;
整数部分很容易,但我不知道分数部分如何得到。
我的初始想法是:
12.345 mod Integer(12.345)
会return0.345,并且可以乘以倒数(本例×1000),但我也不知道如何计算位数。
不是完整的答案,但这会将小数部分作为字符串获取,以便进一步操作以将其作为整数检索:
with Ada.Text_Io;
procedure Remainder is
package Fio is new Ada.Text_IO.Float_IO(Float);
X : constant Float := 12.345;
X_Int : constant Integer := Integer (X);
X_Rem : constant Float := Float'Remainder(X,Float (X_Int));
begin
Fio.Put (X_Rem, Aft => 6, Exp => 0);
end Remainder;
NWS建议使用
X_Int : constant Integer := Integer(Float'Truncation(X));
而不是
X_Int : constant Integer := Integer (X);
否则,浮点数的整个部分可能会向上舍入(例如,如果 X = 12.99,X_Int 将是 13)。
在 Ada 中,我想将 12.345 这样的数字分成两个不同的整数:
whole : integer := 12;
fraction : integer := 345;
整数部分很容易,但我不知道分数部分如何得到。
我的初始想法是:
12.345 mod Integer(12.345)
会return0.345,并且可以乘以倒数(本例×1000),但我也不知道如何计算位数。
不是完整的答案,但这会将小数部分作为字符串获取,以便进一步操作以将其作为整数检索:
with Ada.Text_Io;
procedure Remainder is
package Fio is new Ada.Text_IO.Float_IO(Float);
X : constant Float := 12.345;
X_Int : constant Integer := Integer (X);
X_Rem : constant Float := Float'Remainder(X,Float (X_Int));
begin
Fio.Put (X_Rem, Aft => 6, Exp => 0);
end Remainder;
NWS建议使用
X_Int : constant Integer := Integer(Float'Truncation(X));
而不是
X_Int : constant Integer := Integer (X);
否则,浮点数的整个部分可能会向上舍入(例如,如果 X = 12.99,X_Int 将是 13)。