简体   繁体   English

C++ Arduino - 随机函数不起作用

[英]C++ Arduino - Random Function doesn't work

Hi C++ Devs and StackOverflow users!嗨 C++ 开发者和 StackOverflow 用户!

The code following is what I did, but some reason, random function doesn't work, or output for a result always the same value which is '1', did I do anything wrong?下面的代码是我所做的,但由于某种原因,随机函数不起作用,或者结果的输出总是相同的值,即“1”,我做错了什么吗? How should I fix this issue?我应该如何解决这个问题?

  void setup()           
  {
  int randNumber;
  int i;

  randNumber = random(2);
  Serial.println(randNumber);
  pinMode(PIEZO, OUTPUT);
  delay(3000);

  if (randNumber == 0)
  {
    for (i = 0; i < 105; i++)                                       
    {
      tone(PIEZO, notes[i], time[i]);                                
      delay(time[i]);
    }
  }
  else if (randNumber == 1)                                     
    for (i = 0; i < 116; i++)                                       
    {
      tone(PIEZO, Snowman_Notes[i], Snowman_Rhythm[i]);                                  
      delay(Snowman_Rhythm[i]);
    }
}
void loop()                                                      
{
}

You need to seed random first.您需要先随机播种。 Use randomSeed(seed) .使用randomSeed(seed)

Before using any PRNG (pseudo random number generator), you have to seed the generator.在使用任何 PRNG(伪随机数生成器)之前,您必须为生成器设置种子。 The seed should be different every time otherwise you'll get the same sequence over and over.种子每次都应该不同,否则你会一遍又一遍地得到相同的序列。 That is, if you call randomSeed(2);也就是说,如果你调用randomSeed(2); and then call random() , you'll get the same numbers in the same order every time.然后调用random() ,您每次都会以相同的顺序获得相同的数字。 The pattern of numbers are the same for a given seed.给定种子的数字模式是相同的。 As mentioned in the comments, only seed ONCE per program如评论中所述,每个程序仅种子一次

So, you'll want to seed the PRNG with a different number every time.因此,您每次都希望用不同的数字为 PRNG 设置种子。 Taken from the website , you can just used randomSeed( analogRead(pinNum) );取自网站,您可以使用randomSeed( analogRead(pinNum) ); , where pinNum should be an unconnected pin. ,其中 pinNum 应该是未连接的引脚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM