flex的一些函数随机数random(),round(),ceil(),floor();2008-03-26 16:11Random函数在flash里是非常有用的,可以生成基本的
随机数,创建随机的移动,以及随机的颜色和其他更多的作用。,这个教程将解释如何做出这个例子以及如何利用Random函数产生其
他不同的结果。
基本的Random函数如下
Math.random();
可以产生出0-1之间的任意小数,例如0.0105901374530933 或
0.872525005541986,有几个其他的函数可以用来改变产生的数字,从而可以更好的在你的影片中使用:
Math.round();
Math.ceil();
Math.floor();
这几个函数都是用来取得整数的,Math.round();是采用四舍五入方式取得最接近的整数。Math.ceil();是向上取得一个最接近的整
数,Math.floor();
和Math.ceil();相反,Math.floor();向下 取得一个最接近的整数
如果要创建一个从x到y的随机数,就可以这样写
Math.round(Math.random()*(y-x))+x;
x和y可以是任何的数值,即使是负数也一样
附一產生以當前時間的一個key
sDatetimekey+=mx.controls.DateField.dateToString(dNow,"YYYYMMDD");
sTemp=String(dNow.getHours());
if (sTemp.length==1)
sTemp="0"+sTemp;
sDatetimekey+=sTemp;
sTemp=String(dNow.getMinutes());
if (sTemp.length==1)
sTemp="0"+sTemp;
sDatetimekey+=sTemp;
sTemp=String(dNow.getSeconds());
if (sTemp.length==1)
sTemp="0"+sTemp;
sDatetimekey+=sTemp;
sTemp=String(dNow.getMilliseconds());
if (sTemp.length==1)
sTemp="0"+sTemp;
sDatetimekey+=sTemp;
sTemp=String(Math.round(Math.random()*(9999-1000))+1000);
sDatetimekey+=sTemp;
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ private function getRandom():void{ var r:String=String(Math.round(Math.random()*100)); Alert.show(r,"随机数"); } //获得0到100的随机有整数 ]]> </mx:Script> <mx:Button label="随机" click="getRandom();"/> </mx:Application>