Vbscript很少执行一个函数,有机会使用random

时间:2016-04-25 12:07:47

标签: loops random vbscript call

Vbscript新手。 我用两个参数做了一个随机函数。然后调用它 它导致无限循环打开无限程序。

Function random(v1,v2)
 Randomize
 rdm =(Int((v2 - v1 + 1)* Rnd + v1))
End Function 

Function download()
 Set shell = createobject("wscript.shell"):shell.run "mspaint.exe"   
End function

'I want this download function to run rarely
Do
  Call random(100,1000)
  If  rdm>700 And rdm <760 Then 
  Call download()
  End If
loop

2 个答案:

答案 0 :(得分:2)

将代码添加到return值并添加Exit Do语句以打破循环。

希望这会对你有帮助..

Function random(v1,v2)
 Randomize
 random=(Int((v2 - v1 + 1)* Rnd + v1))
End Function 

Function download()
 Set shell = createobject("wscript.shell"):shell.run "mspaint.exe"   
 download=true
End function

'I want this download function to run rarely
Do
  rdm= random(100,1000)
  If  rdm>700 And rdm <760 Then 
  Call download()
  Exit Do  ' this will break the loop if condition is met 
  End If
loop

答案 1 :(得分:0)

如果您的目的是编写一个脚本,当调用该函数时,调用一个概率为60/900 = 1/15的函数,则会使事情过于复杂。没有理由生成100到1000范围内的随机整数,只是为了检查它是否在某个范围内。如果要以概率p触发操作,请使用如下所示的行:

If rnd() < p Then 'action

如果我了解您的意图,您的整个脚本可以写成:

Randomize

Set shell = createobject("wscript.shell")   

If rnd() < 1/15 Then shell.Run "mspaint.exe"

大多数情况下,你运行上面的脚本没有任何反应,但是它平均会打开油漆的1/15倍。