rand()는 “진짜 랜덤”이 아니라 규칙 기반 숫자 생성srand(time(0))를 한 번만 호출해 실행마다 결과를 바꾼다enum으로 가위/바위/보에 이름을 붙인다rand()는 0부터 RAND_MAX까지의 정수를 반환합니다.rand() % 3을 하면 0, 1, 2 중 하나가 나오므로 “3가지 선택”에 쓸 수 있습니다.srand(seed)는 난수 생성기의 시작 상태를 바꿉니다.srand((unsigned)time(0));를 프로그램 시작 시 딱 한 번 호출합니다.참고:
rand() % 3은 분포가 완벽히 균등하지 않을 수 있지만, 학습/간단 실습 용도로는 충분합니다.
enum RPS { Scissor = 0, Rock = 1, Paper = 2 };
이렇게 해두면, 0 대신 Scissor라고 읽혀서 코드가 훨씬 명확해집니다.
가위/바위/보를 0/1/2로 두면, 아래 규칙으로 승패를 판정할 수 있습니다.
#include <iostream>
#include <cstdlib> // rand, srand
#include <ctime> // time
using namespace std;
enum RPS { Scissor = 0, Rock = 1, Paper = 2 };
const char* ToString(RPS v) {
switch (v) {
case Scissor: return "가위";
case Rock: return "바위";
case Paper: return "보";
default: return "?";
}
}
int main() {
srand((unsigned)time(0)); // 시드 설정(프로그램 시작 시 1회)
while (true) {
cout << "가위(0), 바위(1), 보(2), 종료(9) 입력: ";
int input;
cin >> input;
if (input == 9) break;
if (input < 0 || input > 2) {
cout << "입력이 잘못되었습니다.\n";
continue;
}
RPS player = (RPS)input;
RPS computer = (RPS)(rand() % 3);
cout << "플레이어: " << ToString(player) << ", 컴퓨터: " << ToString(computer) << '\n';
int diff = (player - computer + 3) % 3;
if (diff == 0) cout << "결과: 무승부\n";
else if (diff == 1) cout << "결과: 승리\n";
else cout << "결과: 패배\n";
}
}
srand(time(0))를 매 루프마다 호출하면 어떤 문제가 생길까?enum을 쓰면 0/1/2를 직접 쓰는 것보다 뭐가 좋아질까?