[C언어] 숫자 랜덤으로 뽑기.

빵욱·2024년 3월 15일

C언어에서 숫자를 랜덤으로 뽑으려면 srand, rand, time을 사용한다.

// 사용 
// 랜덤 시드 설정 srand, 랜덤 숫자 rand
// => stdlib.h

// 랜덤 시드가 같으면 숫자가 일정한 패턴으로 발생.
// => time(0)을 시드로 사용하여 항상 다른 숫자가 나오도록 한다.
// time : time.h에 있음.
printf("RAND_MAX = %d\n", RAND_MAX);

RAND_MAX 라고 정의된 수는 rand 함수에서 나올 수 있는 정수 최대값이다.
RAND_MAX는 32767 (2^15 - 1) 이다.
왜 이렇게 크기가 작나 싶어서 찾아봤더니

rand 함수의 반환 값이 기본적으로 15비트 정수 범위 내에 있도록 설계되었기 때문이라고 한다.
이는 역사적인 이유와 호환성을 유지하기 위한 것이라고 하는데, 초기 컴퓨터 시스템에서 메모리와 처리 능력이 제한적이었기 때문에 작은 정수 범위가 일반적이었기 때문이라 그렇다고 한다.

C 표준은 RAND_MAX가 최소 32767 (2^15 - 1)이어야 한다고 규정하고 있다.
즉 최소한 15비트 크기를 가진 정수는 만들 수 있어야 한다는 뜻이다.
하지만 여러 시스템이나 컴파일러에서는 이보다 큰 값을 반환할 수 있도록 RAND_MAX를 더 큰 값으로 설정할 수 있다고 한다.

Ex1

예제로 주사위 [1,6] 의 숫자를 랜덤으로 배열에 담는 코드.

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

int randNumbers[10];
int dice[6];
int MY_RAND_MIN = 1;
int MY_RAND_MAX = 6;

int main()
{
  for (int i = 0; i < 6; i++)
  {
      dice[i] = rand() % MY_RAND_MAX + MY_RAND_MIN;
  }
  
  // 그냥 랜덤으로 숫자 봅기.
  for (int i = 0; i < 10; i++)
  {
      printf("%6d", randNumbers[i]);
  }

}

Ex2

로또 번호 뽑기.
중복된 번호는 제외 Check 메서드를 통해 제외했다.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool Check(int numberArray[], int arrayCount, int comparedNumber);
int main()
{
srand(time(0));

  int numberList[6] = {0};
  int lotto_max = 45;
  int lotto_min = 1;
  int temporaryNum = 0;
  for (int i = 0; i < 6; i++)
  {
  	temporaryNum = rand() % lotto_max + lotto_min;
    if (!Check(numberList, sizeof(numberList) / sizeof(int), temporaryNum))
    {
    	i--;
        continue;
    }
    numberList[i] = temporaryNum;
	 
  }
    
    
   for (int i = 0; i < 6; i++)
    	printf("%6d%c", numberList[i], (i+1) % 6 != 0 ? ' ' : '\n');
   
}

bool Check(int numberArray[], int arrayCount, int comparedNumber)
{
	for (int i = 0; i < arrayCount; i++)
	{
		if (numberArray[i] == comparedNumber)
			return false;
	}
	return true;
}

그나저나 코드블력 들여쓰기가 잘 안된다..

profile
rove drink eat

0개의 댓글