[객체지향프로그래밍(2)] rand()와 srand()의 차이
by 브이담곰1. rand( ) 👉 int rand(void)
Returns a pseudo-random integral number in the range between 0 and RAND_MAX.
This number is gererated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
v1 = rand() % 100; // v1 in the range 0 to 99
v2 = rand() % 100 + 1; // v2 in the range 1 to 100
v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
✔ RAND_MAX
This macro ecpands to an integral constant expression whose value is the maximum value returnded by the rand function.
This value library(<stdlib>)-dependent, but os guaranteed to be at least 32767 an any standard library implemetation.
32767 ≒ 2^16 ≒ 2^10 * 2^6 ≒ 64 * 1Kilo ≒ 64K ≒ 65536 range(-32768~32768)
🙋♀️But, If we use this, the random number sequence out samely all the time!
👉 because, this rand func print from there "seed number" as has certain sequence.
So, we have to set this sequence. if you want to print out as different random numbers.
2. srand(unsigned int seed); 👉 Setting seed number
If the seed is different with each other, the random numbers creat differently.
3. unsigned int seed = time(nullptr);
time(nullptr) is a Unix TimeStamp. We can know the time passed after we started program.
/* srand example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
printf ("First number: %d\n", rand()%100);
srand (time(NULL));
printf ("Random number: %d\n", rand()%100);
srand (1);
printf ("Again the first number: %d\n", rand()%100);
return 0;
}
'programming > C++' 카테고리의 다른 글
[객체지향프로그래밍(2)]Finals Test Report : HelicopterGame만들기. (0) | 2021.12.18 |
---|---|
[객체지향프로그래밍(2)]Finals Test Report : Map Editor만들기. (0) | 2021.12.09 |
[객체지향프로그래밍(2)] Midterm Test Report #2번 풀이 (0) | 2021.11.06 |
[객체지향프로그래밍(2)] Midterm Test Report #1번 풀이 (0) | 2021.11.05 |
[객체지향프로그래밍(2)] 소멸자(Destructor) (0) | 2021.09.14 |
블로그의 정보
농담곰담곰이의곰담농
브이담곰