当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Arduino random()用法及代码示例


[随机数]

说明

random 函数生成伪随机数。

用法

random(max)
random(min, max)

参数

min: 随机值的下限,包括(可选)。
max: 随机值的上限,不包含。

返回

min 和 max-1 之间的随机数。数据类型:long

示例代码

该代码生成随机数并显示它们。

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

注意事项和警告

如果random() 生成的一系列值不同很重要,在随后的草图执行中,使用randomSeed() 使用相当随机的输入初始化随机数生成器,例如未连接引脚上的analogRead()

相反,使用精确重复的伪随机序列有时会很有用。这可以通过在开始随机序列之前使用固定编号调用randomSeed() 来完成。

max 参数应根据存储值的变量的数据类型进行选择。在任何情况下,绝对最大值都与生成的值的 long 特性有关(32 位 - 2,147,483,647)。将max 设置为更高的值不会在编译期间产生错误,但在草图执行期间生成的数字将与预期不同。

相关用法


注:本文由纯净天空筛选整理自arduino.cc大神的英文原创作品 random()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。