产生随机持续时间

A.P*_*cat 2 random duration ada

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

有我的代码:

time : Duration;
time := 0.8;
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*ers 9

The answer is not quite as simple as one might hope. The Ada language provides random number generators for floating point types and for discrete types. The type Duration is a fixed point type. The following code will generate a random duration in the range of 0.500 seconds to 1.300 seconds (with a random variability to the nearest millisecond).

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;
Run Code Online (Sandbox Code Playgroud)