Print Friendly and PDF

C++/C++입문

[C++] 난수

나는야 개발자 2025. 3. 22. 12:42
반응형

time.h 선언

 

srand 선언

srand((unsigned int)time(0));

- 난수를 생성하기 위해 srand를 사용
- srand는 난수를 생성하기 위한 시드값을 설정하는 함수

- time을 이용하는 이유는 실행할 때마다 다른 난수를 생성하기 위함
- srand는 unsigned int를 받아들이기 때문에, time는 unsigned int로 형변환하여 전달한다.

 

난수 생성

//rand는 0~32767까지의 값을 반환한다.(즉 난수 생성)
cout << "난수 생성 : " << rand() << endl;
cout << "난수 생성 : " << rand() << endl;
cout << "난수 생성 : " << rand() << endl;

 

결과

 

연습

//0~99까지의 난수 생성 
cout << "0~99까지의 난수 생성 : " << (rand() % 100) << endl;

//100~200까지의 난수 생성
cout << "100~200까지의 난수 생성 : " << (rand() % 101 + 100) << endl;

//99.9999까지의 난수 생성
cout << "99.9999까지의 난수 생성 : " << (rand() % 10000 / 100.f) << endl;

 

결과

 

반응형