💻 Computer Science/C,C++

[C++] 8강 난수생성과 rand() 이용

bigbigpark 2020. 7. 30. 16:08

오늘은 난수에 대해서 알아봅시다!

난수란? 말 그대로 랜덤한 수 입니다.

긴말 필요없이 예제부터 보시겠습니다


1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <time.h>
using namespace std;
 
int main()
{
    srand((unsigned int)time(0));
 
    cout << rand() << endl;
 
    return 0;
}
cs


자 여기서 처음보는 헤더가 보이실겁니다

2) #include <time.h> 를 적어줍니다

7) srand((unsigned int)time(0)) 은 말씀드리면 조금 복잡하긴 한데, 한 프로그램에서 난수를 여러번 쓰고 싶다할 때

선언해 줍니다. 웬만하면 무조건 쓰시는 걸 권장드립니다.

rand(  )의 리턴값은 int가 허락하는 MAX값까지의 아무 난수가 가져옵니다.



*더 나아가서 나는 0에서 99까지의 난수만 얻고싶다하면 어떻게하면될까요?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <time.h>
using namespace std;
 
int main()
{
    srand((unsigned int)time(0));
 
    cout << rand() % 100 << endl;
    cout << rand() % 100 << endl;
    cout << rand() % 100 << endl;
    cout << rand() % 100 << endl;
    cout << rand() % 100 << endl;
 
    return 0;
}
cs

바로 나머지 연산자 %를 이용하면 됩니다.

rand() % 100 의 결과는 ran()를 100으로 나눈 나머지이므로 0~99가 출력이 됩니다 ㅎㅎ



*더더 나아가서 만약에 50~100까지의 난수만 얻고싶다하면 어떻게하면될까요?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <time.h>
using namespace std;
 
int main()
{
    srand((unsigned int)time(0));
 
    cout << rand() % 51 + 50 << endl;
 
    return 0;
}
cs

코드가 바로 이해되시나요?

rand( )%51 은 0~50까지의 난수이고,

거기다가 50을 더하면 50~100사이의 난수를 얻게됩니다 ㅎㅎ


정말쉽죠?