random()

[Random Numbers]

描述

The random function generates pseudo-random numbers.

語法

random(max)
random(min, max)

參數

min – lower bound of the random value, inclusive (optional)
max – upper bound of the random value, exclusive

回傳

a random number between min 以及 max-1 (long)

注意

If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.

Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling randomSeed() with a fixed number, before starting the random sequence.

範例程式碼

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);
}

參考


語法參考主頁面

86Duino 參考的文本是根據 Creative Commons Attribution-ShareAlike 3.0 License,部分文本是從 the Arduino reference 修改的。 參考中的代碼示例已發佈到公共領域。

發表評論

上部へスクロール