This page is also available in 3 other languages

random()

[Random Numbers]

설명

random 함수는 의사 난수를 만들어 낸다.

문법

random(max)
random(min, max)

매개변수

min - random 값의 하계, inclusive (선택)

max - random 값의 상계, exclusive

반환

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() {
  // 0 에서 299 사이 임의 값 출력
  randNumber = random(300);
  Serial.println(randNumber);

  // 10 에서 19 사이 임의 값 출력
  randNumber = random(10, 20);
  Serial.println(randNumber);

  delay(50);
}

주의와 경고

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.

The max parameter should be chosen according to the data type of the variable in which the value is stored. In any case, the absolute maximum is bound to the long nature of the value generated (32 bit - 2,147,483,647). Setting max to a higher value won’t generate an error during compilation, but during sketch execution the numbers generated will not be as expected.

See also