asp生成随机数

[ 2012-11-23 08:46:57 | 作者: admin ]
字号: | |
简单的产生一个随机数
'rnd() 函数是产生一个0到1之间的浮点数

'获取一个4位的随机数
randomize()
ranNum=int( (9999-1000) * rnd(now())+ 1000) '最大为9999,最小为1000



生成一批不重复的随机数

函数一
'参数说明:c_floor随机数的下限,c_upper随机数的上限,num要生成随机数的个数
'注意:c_floor<c_upper而且都不能为负数,num<=c_upper-c_floor,否则会出现死循环
'调用 call random(1,40,10) 随机产生10个1-40之间的数字

Function random(c_floor,c_upper,num)
     Dim a(),temp,flag,i,j
    
     Redim a(num) '重定义数组
    
     i=1

     Do while i<cint(num)+1

     '生成随机数
       randomize()
       temp=cint(int((cint(c_upper)*rnd())+cint(c_floor)))
       flag=0
    
     '判断生成的随机数时候已经存在,是则重新生成
       for j=1 to ubound(a)
         if cint(temp)=cint(a(j)) then
           flag=1
           Exit for
         End if
       next

     '将生成的随机数存放到数组中
     if flag=0 then
       a(i)=temp
       Response.write a(i) & "<br>"
       i=i+1
     End if

     loop

     random=a '返回一个数组对象
     End function




函数二

response.write rndarray(1,20,10)&"<br>"' 调用过程,显示结果

function rndarray(istart,iend,sum)
'istart和iend是数的开始和结束 sum是你要输出数的个数
dim arrayid(),i,j,blnre,temp,iloop,eloop
redim arrayid(sum-1)
i=0
iloop=0
eloop=0
blnre=false
randomize
do while i<sum
temp=int(rnd*(iend-istart+1)+istart)
if i=0 then
arrayid(0)=temp
i=i+1
iloop=iloop+1
else

for j=0 to i-1
if arrayid(j)=temp then
blnre=true
iloop=iloop+1
exit for'这一句很重要,防止多余的循环
else
iloop=iloop+1
end if
next

   if blnre=false then
   arrayid(i)=temp
   i=i+1
   else
   blnre=false
   end if

end if
eloop=eloop+iloop
iloop=0
loop
rndarray=join(arrayid)&"循环次数:"&eloop
end function


[最后修改由 admin, 于 2013-06-27 10:34:08]
评论Feed 评论Feed: http://blog.xg98.com/feed.asp?q=comment&id=1908

这篇日志没有评论。

此日志不可发表评论。