rand

의사 난수를 생성합니다. 이 함수의 보다 프로그래밍 방식으로 안전한 버전을 사용할 수 있습니다. 를 참조하세요 rand_s. 생성된 rand 숫자는 암호화된 보안이 아닙니다. 보다 암호화적으로 안전한 난수 생성을 위해 C++ 표준 라이브러리<random>에 선언된 함수를 사용합니다rand_s.

구문

int rand(void);

반환 값

rand는 위에서 설명한 대로 의사 난수를 반환합니다. 오류 반환이 없습니다.

설명

rand 함수는 0부터 RAND_MAX(32767) 범위의 의사 난수 정수를 반환합니다. 함수를 srand 사용하여 호출 rand하기 전에 의사-숫자 생성기를 시드합니다.

함수는 rand 잘 알려진 시퀀스를 생성하며 암호화 함수로 사용하기에 적합하지 않습니다. 보다 암호화적으로 안전한 난수 생성을 위해 C++ 표준 라이브러리<random>에 선언된 함수를 사용합니다rand_s.

기본적으로 이 함수의 전역 상태는 애플리케이션으로 범위가 지정됩니다. 이 동작을 변경하려면 CRT의 전역 상태를 참조하세요.

요구 사항

루틴에서 반환된 값 필수 헤더
rand <stdlib.h>

호환성에 대한 자세한 내용은 호환성을 참조하세요.

예시

// crt_rand.c
// This program seeds the random-number generator
// with a fixed seed, then exercises the rand function
// to demonstrate generating random numbers, and
// random numbers in a specified range.

#include <stdlib.h> // rand(), srand()
#include <stdio.h> // printf()

void SimpleRandDemo(int n)
{
    // Print n random numbers.
    for (int i = 0; i < n; i++)
    {
        printf("  %6d\n", rand());
    }
}

void RangedRandDemo(int range_min, int range_max, int n)
{
    // Generate random numbers in the interval [range_min, range_max], inclusive.

    for (int i = 0; i < n; i++)
    {
        // Note: This method of generating random numbers in a range isn't suitable for
        // applications that require high quality random numbers.
        // rand() has a small output range [0,32767], making it unsuitable for
        // generating random numbers across a large range using the method below.
        // The approach below also may result in a non-uniform distribution.
        // More robust random number functionality is available in the C++ <random> header.
        // See https://learn.microsoft.com/cpp/standard-library/random
        int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min;
        printf("  %6d\n", r);
    }
}

int main(void)
{
    // Seed the random-number generator with a fixed seed so that
    // the numbers will be the same every time we run.
    srand(1792);

    printf("Simple random number demo ====\n\n");
    SimpleRandDemo(10);
    printf("\nRandom number in a range demo ====\n\n");
    RangedRandDemo(-100, 100, 100000);
}```

```Output
Simple random number demo ====

    5890
    1279
   19497
    1207
   11420
    3377
   15317
   29489
    9716
   23323

Random number in a range demo ====

     -82
     -46
      50
      77
     -47
      32
      76
     -13
     -58
      90

참고 항목

수학 및 부동 소수점 지원
srand
rand_s
C++ <random> 라이브러리