更新时间:2022-12-25 22:02:54
我认为前 3 个答案中的任何一个都不正确,所以让我尝试一下:您说的是时间在流逝,并且在每个N 秒的切片,您希望在该切片中的随机时间发生一个事件.如果是这样,那么每当时间是 N 秒的倍数时,获取 0 到 N 之间的随机数,并在该时间生成事件.例如,在伪代码中:
I don't think any of the first 3 answers have it right, so let me try: what you are saying is that time is ticking, and in each slice of N seconds, you want one event to occur at a random time in that slice. If that is the case, then whenever the time is a multiple of N seconds, get a random number between 0 and N, and generate the event at that time. For example, in pseudo-code:
time = 0
delta_time = 1 second
max_time = 100 seconds
slice_time = 10 seconds
// decide when event of first slice will occur; can't be at 0: get random #
// in range [delta_time, slice_time]:
next_rand_time = random(delta_time, slice_time)
setup timer to fire at interval of delta_time, each time do the following (callback):
time += delta_time
// is it time to fire the event yet? allow for round-off error:
if abs(time - next_rand_time) < 0.0001:
generate event
// is it time to decide when next random event will be?
if modulo(time, slice_time) == 0:
// can't be on left boundary; get random # in range [delta_time, slice_time]:
next_rand_time = time + random(delta_time, slice_time)
这 5 个变量(时间、delta_time 等)很可能是使用计时器的类的数据成员,而回调将是该类的一个方法.在您的帖子中提供一些代码以获取更多详细信息.
The 5 variables (time, delta_time, etc) are likely going to be data members of the class that uses the timer, and the callback will be a method of the class. Provide some code in your post for further details.