生成随机持续时间
Generate a random duration
我想知道如何在ada中生成一个随机的Duration。
这是我的代码:
time : Duration;
time := 0.8;
如何给 time
添加一个介于 0.5 和 1.3 之间的随机值?
答案并不像人们希望的那么简单。 Ada 语言为浮点类型和离散类型提供了随机数生成器。 Duration 类型是定点类型。
以下代码将生成 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;
我想知道如何在ada中生成一个随机的Duration。
这是我的代码:
time : Duration;
time := 0.8;
如何给 time
添加一个介于 0.5 和 1.3 之间的随机值?
答案并不像人们希望的那么简单。 Ada 语言为浮点类型和离散类型提供了随机数生成器。 Duration 类型是定点类型。 以下代码将生成 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;