random()
描述
random 函式會產生一個偽隨機性的數字。
語法
random(max)
random(min, max)
參數
min – 隨機值的下限,包含下限 (非必要)
max – 隨機值的上限,不包含上限
回傳
一個介於 min 到 max-1 之間的數字 (資料型別是 long)
注意
如果希望由 random() 產生的數字具有高隨機性,在程式碼中可以用 randomSeed() 去引入一個真正隨機的輸入,數值的隨機性就如同 pin 腳上不接類比輸入電壓就呼叫 analogRead()。
相反的,它的偽隨機性在需要重現相同行為時非常有用;可以在每一次開始隨機序列之前呼叫 randomSeed() 並給它固定的參數值。
範例
long randNumber;
void setup(){
Serial.begin(9600);
// 如果 pin 0 的類比輸入不連接到任何東西,
// analogRead() 會讀取到隨機類比訊號值,
// 這有助於 randomSeed() 在每次程式運行時產生不同的種子數字,
// 然後讓 random 函式產生的數值更加隨機。
randomSeed(analogRead(0));
}
void loop() {
// 印出介於 0 到 299 的隨機數字
randNumber = random(300);
Serial.println(randNumber);
// 印出介於 10 到 19 的隨機數字
randNumber = random(10, 20);
Serial.println(randNumber);
delay(50);
}
See also
- randomSeed()
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.
