问题
我要模拟硬币投掷或布尔事件来达到 50%几率成功。
解决办法
用 NumberUtilities.random( ) 方法产生 0 到 1 的整数,根据每种可能得出结果。
讨论
用 random( ) 方法产生指定范围的随机整数,能够产生两个结果对应硬币的正面和反面状态,在程 序里我们用 0 代表一个状态,1 代表另一状态,当然你用 1 和 2 也是可以的,总之是 2 个状态,这 样就能模拟硬币投掷了:
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;
import ascb.util.NumberUtilities;
public class CoinExample extends Sprite {
private var _field:TextField;
public function CoinExample( ) {
_field = new TextField( );
_field.autoSize = "left";
addChild(_field);
var circle:Sprite = new Sprite( ); circle.graphics.beginFill(0, 100); circle.graphics.drawCircle(100, 100, 100); circle.graphics.endFill( ); circle.addEventListener(MouseEvent.CLICK, onClick); addChild(circle);
}
private function onClick(event:MouseEvent):void {
var randomNumber:Number = NumberUtilities.random(0, 1);
_field.text = (randomNumber == 0) ? "heads" : "tails";
}
}
}
记录正反面出现次数:
package {
import flash.display.Sprite;
import flash.text.TextField;
import ascb.util.NumberUtilities;
public class CoinTest extends Sprite {
private var _field:TextField;
public function CoinTest( ) {
_field = new TextField( );
_field.autoSize = "left";
addChild(_field);
var heads:Number = 0;
var tails:Number = 0;
var randomNumber:Number;
for(var i:Number = 0; i < 10000; i++) { randomNumber = NumberUtilities.random(0, 1); if(randomNumber == 0) {
heads++;
}
else {
tails++;
}
}
_field.text = "heads: " + heads + ", tails: " + tails;
}
}
}
如果要测试随机数,应该保存在变量中,像上面的代码,下面代码的统计是错误的,因此 else if 每
次都产生新的随机数:
package {
import flash.display.Sprite;
import ascb.util.NumberUtilities;
public class RandomLetter extends Sprite {
public function RandomLetter( ) { for(var i:Number = 0; i < 10000; i++) { trace(getRandomLetter( ));
}
}
private function getRandomLetter( ):String {
if(NumberUtilities.random(0, 2) == 0) {
return "A";
}
else if(NumberUtilities.random(0, 2) == 1) {
return "B";
}
else if(NumberUtilities.random(0, 2) == 2) {
return "C";
}
// It's possible that none of the preceding will evaluate to true,
// and the method will reach this point without returning a valid
// string. return "";
}
}
}
下面才正确:
package {
import flash.display.Sprite;
import ascb.util.NumberUtilities;
public class RandomLetter extends Sprite {
public function RandomLetter( ) { for(var i:uint = 0; i < 10000; i++) { trace(getRandomLetter( ));
}
}
private function getRandomLetter( ):String {
// random( ) 返回结果到变量上
var randomInteger:uint = NumberUtilities.random(0, 2);
if(randomInteger == 0) {
return "A";
}
else if(randomInteger == 1) {
return "B";
}
else if(randomInteger == 2) {
return "C";
}
return "";
}
}
}
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |