C,C++/개념 실습 프로그래밍
[c언어]중복없는 난수 생성하기 method_2
luckybee
2022. 9. 25. 20:43
728x90
반응형
중복 없는 난수 생성하기 두 번째 방법이다. 아래 코드를 보자.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int arr[10]; //난수가 저장될 배열
int count = 0; //난수가 확정된 숫자의 개수
int value, i; //반복문에서 사용할 변수
srand((unsigned int)time(NULL)); //난수 발생의 기준값 초기화
while (count<10) //배열 크기가 10이니까 10번 반복
{
value = rand() % 10; //0~9의 난수 발생
for (i = 0; i < count; i++){ //난수가 중복인지 탐색
if (arr[i]==value){
break;
}
}
if (i==count){ //count와 i가 같으면 중복 난수는 없다는 뜻임
arr[i] = value; //값 대입
count++; //count++
}
}
for (int i = 0; i < 10; i++){
printf("%d ", arr[i]); //출력
}
}
성공적으로 난수가 중복없이 생성되었다.
728x90
반응형