产生随机持续时间

皮西卡特

我想知道如何在ada中生成随机的Duration。

有我的代码:

time : Duration;
time := 0.8;

如何time在0.5到1.3之间添加一个随机值

吉姆·罗杰斯

答案并不像人们希望的那么简单。Ada语言为浮点类型和离散类型提供随机数生成器。持续时间类型是定点类型。以下代码将生成一个介于0.500秒至1.300秒之间的随机持续时间(随机变化至最接近的毫秒)。

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

procedure Main is

   Random_Duration : Duration;
   type Custom is range 500..1300;
   package Rand_Cust is new Ada.Numerics.Discrete_Random(Custom);
   use Rand_Cust;
   Seed : Generator;
   Num  : Custom;
begin
   -- Create the seed for the random number generator
   Reset(Seed);

   -- Generate a random integer from 500 to 1300
   Num := Random(Seed);

   -- Convert Num to a Duration value from 0.5 to 1.3
   Random_Duration := Duration(Num) / 1000.0;

   -- Output the random duration value
   Put_Line(Random_Duration'Image);
end Main;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章