#include <iostream>
#include <cstdlib> //std::radn(), std::srand()
#include <ctime> //std::time()
using namespace std;
/*특정한 정수 사이의 random 넘버*/
int getRandomNumber(int min, int max)
{
static const double fraction = 1.0 / (RAND_MAX + 1.0);
//RAND_MAX는 random넘버를 만들 때 나올 수 있는 가장 큰 숫자
return min + static_cast<int>((max - min + 1)*(std::rand()*(fraction)));
}
int main()
{
std::srand(static_cast<unsigned int>(std::time(0))); //seed를 바꾸는
//debuging할 때는 seed를 고정
for (int count = 1; count <= 100; ++count)
{
cout << getRandomNumber(5,8) << "\t";
if (count % 5 == 0) cout << endl;
}
return 0;
}
랜덤 라이브러리를 사용해서 난수생성(주로 사용)
#include <iostream>
#include <cstdlib> //std::radn(), std::srand()
#include <ctime> //std::time()
#include <random>
using namespace std;
int main()
{
std::random_device rd;
std::mt19937_64 mersenne(rd());
//create a mersenne twister(random time과 비슷한 역할)
std::uniform_int_distribution<> dice(1, 6);
for (int count = 1; count <= 20; ++count)
cout << dice(mersenne) << endl;
return 0;
}
'programming > c++' 카테고리의 다른 글
6.3 배열과 반복문 (0) | 2019.05.06 |
---|---|
6.1 배열 기초적인 사용법 (0) | 2019.05.06 |
5.8 break, continue (0) | 2019.05.04 |
5.7 반복문 for (0) | 2019.05.04 |
5.6 do while (0) | 2019.04.30 |