Making a small app, and I want a function to execute 50% of the time. So if I were to dbl click the exe half the time the function would execute, and the other half it wouldn't. I can't seem to find anyway to easily do this, the one solution I tried seemed to determine the chance on compile rather than on run. Thanks in advance!
pieguy
问问题
217 次
4 回答
4
不要忘记播种随机发生器!否则,它每次都会给你相同的价值。您使用“”播种它Randomize Timer
,例如:
Private Sub Main()
Randomize Timer
If Rnd > 0.5 Then
ExecuteFunction ()
End If
End Sub
于 2008-10-25T10:19:00.943 回答
4
Generate a random decimal number between 0 and 1. If it is greater than 0.5 run, if it is less than or equal to 0.5 do not run.
于 2008-10-25T05:20:07.583 回答
2
For example:
Private Sub Main()
If Rnd > 0.5 Then
ExecuteFunction ()
End If
End Sub
于 2008-10-25T05:26:13.907 回答
1
如果您希望它随机运行,其他人已经提供了该解决方案。如果您想要一个更具确定性的行为(它必须准确地每秒钟运行一次),您将需要在执行之间存储状态。
您可以通过(例如)尝试从文件中读取整数(如果文件不存在,将其设置为零)将状态保存在注册表或文件系统中,加 1 并将其写回同一个文件。
如果写回的数字是偶数,则运行您的函数,否则退出。
这样,您将在执行和不执行之间交替。
于 2008-10-25T06:30:29.127 回答