Random()
從 YFRobotwiki
描述
隨機函數產生偽隨機數。
語法
random(max) random(min, max)
參數
- min - 隨機值的下限,包括(可選)
- max - 隨機值的上限,不包含
返回
- min和max-1之間的隨機數(long)
注意
如需要在一個random()序列上生成真正意義的隨機數,在執行其子序列時使用randomSeed()函數預設一個絕對的隨機輸入,例如在一個斷開引腳上的analogRead()函數的返回值。
反之,有些時候偽隨機數的精確重複也是有用的。這可以在一個隨機系列開始前,通過調用一個使用固定數值的randomSeed()函數來完成。
示例
long randNumber; void setup(){ Serial.begin(9600); // if analog input pin 0 is unconnected, random analog // noise will cause the call to randomSeed() to generate // different seed numbers each time the sketch runs. // randomSeed() will then shuffle the random function. randomSeed(analogRead(0)); } void loop() { // print a random number from 0 to 299 randNumber = random(300); Serial.println(randNumber); // print a random number from 10 to 19 randNumber = random(10, 20); Serial.println(randNumber); delay(50); }
擴展閱讀
更多建議和問題歡迎反饋至 YFRobot論壇