BE/C++

[C++] 배열을 이용한 로또당첨 숫자 맞추기

콩다영 2023. 10. 26.
728x90

배열을 이용하여 로또번호 1~45까지의 6개 숫자 맞추기 프로그램을 구현해보자.

 

 

[ 적용조건 ]

▷ 컴퓨터가 1~45까지의 수 중 랜덤으로 6개의 수 지정 (중복 x)

사용자도 1~45까지의 수 중 원하는 숫자 6개 입력 (중복 x)

두 배열을 비교해서 몇 등인지 출력하기!

     : 한 개도 맞추지 못하면 7등, 1개만 맞추면 6등, 2개 맞추면 5등... 6개를 모두 맞추면 1등

 

 

실행코드

#include <iostream>
#include <cstdlib>
#include <random>

// 로또번호(랜덤 숫자) 맞추기

using std::cout;
using std::cin;
using std::endl;

int main() {
	int inputNum = 0, num, cnt = 0;
	bool isSame = false;
	int lotto[6] = {}, inNumAry[6] = {};

	std::srand(time(NULL));

	// 1~45 랜덤숫자 발행 (중복X)
	while (cnt < 6) {
		isSame = false;
		num = std::rand() % 45 + 1;
		for (int i = 0; i < cnt; i++) {
			if (lotto[i] == num) {
				//중복 발생.
				isSame = true;
				break;
			}
		}
		if (!isSame) {
			lotto[cnt] = num;
			cnt++;
		}
	}


	// 1~45 6개 숫자입력 (중복X)
	cout << "☆ ☆ ☆  행운의 로또번호 맞추기  ☆ ☆ ☆" << endl;
	cout << "(숫자는 1~45까지의 숫자만 입력할 수 있습니다.)" << endl;
	cnt = 0;
	while (cnt < 6) {
		isSame = false;
		cout <<"\n" << cnt + 1 << "번째 숫자를 입력하세요 : ";
		cin >> inputNum;
		if (inputNum > 45 || inputNum < 1) {
			cout << "잘못된 숫자입니다. 다시 입력해주세요." << endl;
		}
		else {
			for (int i = 0; i < cnt; i++) {
				if (inNumAry[i] == inputNum) {
					//중복 발생.
					cout << "이미 입력된 숫자입니다." << endl;
					isSame = true;
					break;
				}
			}
			if (!isSame) {
				inNumAry[cnt] = inputNum;
				cnt++;
			}
		}
	}


	cout << "\n--------------------------------------" << endl;
	cout << "☆ 로또번호 : ";
	int sameCnt = 0;
	for (int i = 0; i < 6; i++) {
		cout << lotto[i] << " ";

		for (int j = 0; j < 6; j++) {
			if (lotto[i] == inNumAry[j]) {
				sameCnt++;
			}
		}
	}
	cout << endl;
	cout << "  ☞ 내번호 : ";
	for (int i = 0; i < 6; i++) {
		cout << inNumAry[i] << " ";
	}
	cout << endl;
	cout << "\n--------------------------------------" << endl << endl;

	// 6개 모두 맞추면 1등, ..., 한 개도 맞추지 못하면 7등
	cout << "\n1 ~ 7등까지 결과가 나올 수 있습니다." << endl << endl;
	cout << "▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼" << endl;
	cout << "  ☞ 결과 : " << (7 - sameCnt) << "등 입니다 !" << endl;
	cout << "▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲" << endl;

 

실행결과

[C++] 배열을 이용한 로또당첨 숫자 맞추기 - undefined - 실행결과

 

느낀 점

: 실제 로또번호처럼 보너스번호도 합산한 등수 추출방법을 구현해보고 싶다!

그리고 나도 로또당첨되고 싶다...  ㅎ_ㅎ

 

728x90
반응형

댓글