rand() 함수를 사용하여 C++에서 난수를 생성할 수 있습니다. srand() 함수는 rand()에서 사용하는 난수 생성기를 시드합니다.
rand() 및 srand()를 사용하는 프로그램은 다음과 같습니다. -
예시
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand(1);
for(int i=0; i<5; i++)
cout << rand() % 100 <<" ";
return 0;
} 출력
위 프로그램의 출력은 다음과 같습니다 -
83 86 77 15 93
위의 프로그램에서 출력은 srand(1)이 사용될 때 실행되는 모든 프로그램에서 동일합니다.
프로그램을 실행할 때마다 난수 시퀀스를 변경하기 위해 srand(time(NULL))이 사용됩니다. 이를 입증하는 프로그램은 다음과 같습니다. -
예시
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
srand(time(NULL));
for(int i=0; i<5; i++)
cout << rand() % 100 <<" ";
return 0;
} 출력
위 프로그램의 출력은 다음과 같습니다 -
63 98 17 49 46
동일한 프로그램의 다른 실행에서 얻은 출력은 다음과 같습니다 -
44 21 19 2 83