본문 바로가기

Programming/C++

C++ 난수 random number 만들기

#include <iostream>
#include <cstdlib> //std::radn(), std::srand()
#include <ctime>

using namespace std;

int main()
{
    //std::srand(5343); //seed를 설정해주는 것
    //다만 이렇게 되면 seed number가 고정이 된다.
    //그래서 srand를 time과 연결시켜준다
    std::srand(static_cast<unsigned int>(std::time(0)));

    for (int i = 0; i < 100; i++)
    {
        cout << std::rand() << "\t";

        if (i % 5 == 0)
            cout << endl;
    }

    return 0;
}

seed number를 기준으로 그에 대한 random한 숫자를 생성한다.

seed number가 동일하다면 동일한 random number를 생성한다.

 

그래서 time에 seed number를 걸어서 random한 숫자를 생성한다.

 

 

**** 다만 디버깅 같은 경우에는 seed number를 고정시켜야 한다. 

 


특정 number 사이에 random number를 발생시키는 함수 

 

#include <iostream>
#include <cstdlib> //std::radn(), std::srand()
#include <ctime>

using namespace std;

int getRandomNumber(int min, int max)
{
    static const double fraction = 1.0 / (RAND_MAX + 1.0);

    return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}

int main()
{
    std::srand(static_cast<unsigned int>(std::time(0)));

    for (int i = 0; i < 100; i++)
    {
        cout << getRandomNumber(5, 8) << "\t";

        if (i % 5 == 0)
            cout << endl;
    }

    return 0;
}
#include <iostream>
#include <cstdlib> //std::radn(), std::srand()
#include <ctime>

using namespace std;

int main()
{
   
    std::srand(static_cast<unsigned int>(std::time(0)));

    for (int i = 0; i < 100; i++)
    {
        cout << rand() % 4 + 5 << "\t";

        if (i % 5 == 0)
            cout << endl;
    }

    return 0;
}

두번째와 같은 방법으로 하면 첫번째와 비슷한 결과가 나오지만 나누기라 속도가 조금 느릴 수 있다. 

그리고 숫자가 커지면 특정 영역으로 몰릴 수 있다. 

 


random library를 이용한 random number 생성 방법

#include <iostream>
#include <cstdlib> //std::radn(), std::srand()
#include <ctime>
#include <random>

using namespace std;

int main()
{
    //random divice를 만들고
    random_device rd;
    //생성기 64bit짜리 난수를 생성
    //mesenne는 변수명이고 create a mesenne twister,
    mt19937_64 mersenne(rd());
    //1~6 사이의 선택이 된다. 확률은 동일하게 나옴
    uniform_int_distribution<> dice(1, 6);

    for (int i = 0; i < 20; i++)
    {
        cout << dice(mersenne) << endl;
    }

    return 0;
}

'Programming > C++' 카테고리의 다른 글

C++ 메모리 동적 할당, 동적 할당 배열  (0) 2021.03.15
c++ Pointer의 기초  (0) 2021.03.14
C++ 배열의 반복  (0) 2021.03.14
C++ 배열의 기초  (0) 2021.03.08
C++ Fundamental data Types, Integers, Float, Char type  (0) 2021.02.09