random()

描述

random 函式会产生一个伪随机性的数字。

语法


random(max)
random(min, max)

参数

min 随机值的下限,包含下限 (非必要)
max 随机值的上限,不包含上限

回传

一个介于 minmax-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.