976회차 당첨번호 : 4, 12, 14, 25, 35, 37 + 2(보너스 번호)
- 난수 사용(srand, rand, time.h)
- goto문 사용 : goto문은 코드 길이를 줄여주지만 가독성이 아주 떨어집니다.
- Sleep() 함수 사용 / Windows 헤더 파일 include
* srand와 rand의 차이점
srand는 일련의 규칙성을 가지고 난수를 생성하고, rand는 규칙성 없이 여러 개의 패턴으로 난수를 생성합니다.
로또 번호 추출하기
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<Windows.h>
void sortArr(int* lotto, int length) { //난수로 추출한 번호 정렬
for (int i = 0; i < length - 2; i++) {
for (int j = i + 1; j < length - 1; j++) {
if (lotto[i] > lotto[j]) {
int temp = lotto[i];
lotto[i] = lotto[j];
lotto[j] = temp;
}
}
}
}
void main() {
int r = 0;
int lotto[7] = { 0, };
int lottoWin[7] = { 4, 12, 14, 25, 35, 37, 2 };
int length = sizeof(lotto) / sizeof(int);
int count = 0;
printf("========당첨 번호========\n");
for (int i = 0; i < length; i++) {
printf("%d ", lottoWin[i]);
}
printf("\n=========================\n");
printf("\n");
srand(time(NULL)); //실행할 때마다 새로운 난수를 생성해줌.
for (int i = 0; i < length; i++) {
again:;
r = rand() % 45 + 1;
for (int j = 0; j < i; j++) { //같은 번호 출력 방지
if (r == lotto[j])
goto again;
}
lotto[i] = r;
}
printf("=======나의 로또 번호========\n");
for (int i = 0; i < length; i++) {
printf("%d ", lotto[i]);
Sleep(1000);
}
printf("\n\n");
printf("보너스 번호 : %d\n\n", lotto[length - 1]);
printf("=============================\n");
sortArr(lotto, length);
sortArr(lottoWin, length);
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (lotto[j] <= lottoWin[i])
if (lotto[j] == lottoWin[i])
count++;
}
}
if (count == 6)
if (lotto[6] == lottoWin[6])
printf("2등 당첨!\n");
else
printf("1등 당첨!\n");
else if (count == 5)
printf("3등 당첨!\n");
else if (count == 4)
printf("4등 당첨!\n");
else if (count == 3)
printf("5등 당첨!\n");
else
printf("낙점ㅠㅠ\n");
printf("개수 : %d\n", count);
}
* srand(time(NULL)) : srand를 통해 time함수를 NULL로 설정해주지 않으면 실행할 때마다 같은 숫자가 출력됨.


최소 숫자 3개까지는 맞춰보려고 여러 번 실행했는데 2개 이상 맞지 않네요...ㅠㅠ
감사합니다!
2021.08.16~17
'C언어' 카테고리의 다른 글
[C언어] 동적할당 (dynamic allocation) (0) | 2021.09.06 |
---|---|
[자료구조 - C언어] 정렬(Sort) - Bubble, Insertion, Selection (0) | 2021.08.30 |
[C언어] 구조체(2) - 예제 (0) | 2021.08.08 |
[C언어] 구조체(1) (0) | 2021.08.07 |
[C언어] 1차원 배열 (0) | 2021.08.03 |