Random():修訂版本之間的差異

出自YFRobotwiki
跳轉到: 導覽搜尋
(以“<font color="orange" size="+1">'''描述'''</font> 随机函数产生伪随机数。 <font color="orange" size="+1">'''语法'''</font> <pre style="color:dimgray...”为内容创建页面)
 
 
第 39 行: 第 39 行:
 
   Serial.begin(9600);
 
   Serial.begin(9600);
  
   // if analog input pin 0 is unconnected, random analog
+
   // if analog input pin 0 is unconnected, random analog     如果模拟输入引脚0为断开,随机的模拟噪声
   // noise will cause the call to randomSeed() to generate
+
   // noise will cause the call to randomSeed() to generate   将会调用randomSeed()函数在每次代码运行时生成
   // different seed numbers each time the sketch runs.
+
   // different seed numbers each time the sketch runs.       不同的种子数值。
   // randomSeed() will then shuffle the random function.
+
   // randomSeed() will then shuffle the random function.     randomSeed()将随机打乱random函数。
 
   randomSeed(analogRead(0));
 
   randomSeed(analogRead(0));
 
}
 
}
  
 
void loop() {
 
void loop() {
   // print a random number from 0 to 299
+
   // print a random number from 0 to 299   打印一个0到299之间的随机数
 
   randNumber = random(300);
 
   randNumber = random(300);
 
   Serial.println(randNumber);   
 
   Serial.println(randNumber);   
  
   // print a random number from 10 to 19
+
   // print a random number from 10 to 19   打印一个10到19之间的随机数
 
   randNumber = random(10, 20);
 
   randNumber = random(10, 20);
 
   Serial.println(randNumber);
 
   Serial.println(randNumber);

2017年9月13日 (三) 14:14的最新修訂版本

描述

隨機函數產生偽隨機數。


語法

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     如果模拟输入引脚0为断开,随机的模拟噪声
  // noise will cause the call to randomSeed() to generate   将会调用randomSeed()函数在每次代码运行时生成
  // different seed numbers each time the sketch runs.       不同的种子数值。
  // randomSeed() will then shuffle the random function.     randomSeed()将随机打乱random函数。
  randomSeed(analogRead(0));
}

void loop() {
  // print a random number from 0 to 299   打印一个0到299之间的随机数
  randNumber = random(300);
  Serial.println(randNumber);  

  // print a random number from 10 to 19   打印一个10到19之间的随机数
  randNumber = random(10, 20);
  Serial.println(randNumber);

  delay(50);
}


擴展閱讀

- randomSeed()




返回Arduino語法參考列表

更多建議和問題歡迎反饋至 YFRobot論壇