首页 > 解决方案 > 生成随机持续时间

问题描述

我想知道如何在 ada 中生成随机持续时间。

有我的代码:

time : Duration;
time := 0.8;

如何将随机值添加到time0.5 和 1.3 之间?

标签: randomadaduration

解决方案


答案并不像人们希望的那么简单。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;

推荐阅读