C_C++/C_라이브러리_함수

(C/C++) srand: 난수를 초기화한다

고니자니 2022. 12. 8. 08:47
반응형
#include <stdlib.h>
void srand(undigned seed);

srand 함수는 seed 값이 1인 난수표상의 난수를 새로운 시작점으로 초기화합니다.

 

 

C언어 코드

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
	int i;
    
	srand((unsigned)time(NULL));   // 난수 초기화: 매번 다른 난수를 생성하게 함
    
	for (i = 0; i < 10; i++)
		printf("%d\n", rand());
}

 

 

위의 C언어 코드를 C++로 변경하면 다음과 같습니다.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
	srand((unsigned int)time(NULL)); //seed 값으로 현재 시간을 사용 

	for(int i=0;i<10;i++)
		cout << rand() %100 << " ";
	cout << endl;
}

 

 

 

반응형

 

 


 

 

 

(C언어) rand() 함수 정리

#rand #rand() #srand() #srand #난수 #난수생성 #임의의수 #실수난수 rand() 함수 0부터 RAND_MAX(32767) 범위의 임의의 난수를 생성합니다. 이 함수는 정수를 생성합니다. 실수를 생성하는 방법은 아래쪽에 설

gonyzany.tistory.com

 

 

728x90
반응형