티스토리 뷰

 

난수(Random Number)

특정한 배열 순서나 규칙을 가지지 않는 연속적인 임의의 수를 말한다


c언어에서는 시스템 라이브러리에서 난수를 만드는 함수를 제공한다

r​and 함수는 c++ c++에 내장된 난수표에 있는 수를 가져올 뿐이기 때문에 항상 일정한 수를 출력한다.

난수표에서 시드와 횟수에 따라 수를 불러오는 함수이다.

항상 같은 수만 출력되면 난수의 의미가 없어지기 때문에

srand(시드의번호); 로 난수표의 시드를 바꾸어주어야 한다.

srand(1) 로 했을 경우 그냥 rand() 함수만 썼을 때와 같은 수가 나옴

즉 그냥 rand 함수만 쓰게되면 난수표의 시드(seed)가 1인것을 알 수 있다.

srand(2) 로 하면 값변한다 -> 2번 시드를 불러오기 때문

c++에서 시드의 범위는 0 ~ 32767

srand() 사용할 때마다 일일히 시드값을 지정해 넣어 줄 수가 없기 때문에

시드를 계속 바꾸어 넣어줄 수 있는 함수를 이용하면

진정한 난수를 얻을 수 있다.


ex)

windows.h 에 정의 된 GetTickCount()함수

(컴터 부팅되고 난 이후의 시간 줌 1/1000초 단위)

=>  srand(GetTickCount);


time.h에 정의된 time() 함수


 => srand( (unsigned)time( NULL ) );



rand() % n + m

이런식으로 사용하면 원하는 범위 내의 랜덤값이 나오게ㅉ;



 

 

 

 

 

 

 


[function] rand 함수 

Generates a pseudorandom number.

a more secure version of this function is available, see rand_s.

syntax

int rand (void);


raturn value

rand returns a pseudorandom number, as described above. There is no err return.


remarks

The rand function returns a pseudorandom integer in the range 0 to RAND_MAX(32767). Use the srand fucntion to seed the pseudorandom number generator befor calling rand.


requierments

routine : rand

required header <stdlib.h>



pseudorandom 의사난수

generate 발생시키다 만들어내다

 as descrived above 위에 설명된대로


[function] rand_s 함수 

Generates a pseudorandom number.

A version of rand with security enhancements as described in Security Features in the CRT.


syntax

erron_t rand_s (unsigned int* randomValue);


raturn value

Zero if successful, otherwise, an error code. If the input pointer randomValue is a null pointer, the function invokes an invalid parameter handler, as descrived in Parameter Validation. if excution is allowed to continue, the function returns EINVAL and aets errno th EINVAL. if the fucntion fails for any ather reason, *randomvalue is set to 0.


//얘에 대한 나머지 설명은

https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx



[function] srand 함수 

Sets the starting seed value for the pseudorandom number generator.

syntax

void srand(unsigned int seed);


parameters

seed  Seed for pseudorandom number generation


remarks

the srand function sets the starting point for generating a series of pseudorandom integers in the current thread. To create the same sequence of results, call the srand function and use the same seed argument again. Any other value for seed sets the generator to a different starting point int he pseudorandom sequence. rand retrieves the pseudorandom numbers that are generated. Calling rand befor any call to srand generators the same sequence as calling srand with seed passed as 1.




Random class 에 관해 더알고싶다면

https://msdn.microsoft.com/library/system.random.aspx

 

 

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

[keyword] static 정적변수 정적함수 정적멤버변수  (0) 2017.07.03
읽고 싶지 않은 문자가 있을 때  (0) 2017.06.23
클래스 안의 클래스 접근  (0) 2017.06.11
예약어  (0) 2017.06.10
main 함수에게 return 이란?  (0) 2017.06.10
댓글