void main() { int input, computer; srand((int)time(NULL)); while(1) { cout << "가위(0), 바위(1), 보(2), 종료(3) : "; cin >> input; if((input < 0) || (input > 3)) { cout << "다시 입력해 주세요!" << endl << endl; continue; } if(input == 3) break; computer = rand() % 3; if(computer == input) { cout << "비겼습니다." << endl << endl; } else if((computer == 0) && (input == 1)) { cout << "이기셨습니다." << endl << endl; } else if((computer == 0) && (input == 2)) { cout << "지셨습니다." << endl << endl; } else if((computer == 1) && (input == 2)) { cout << "이기셨습니다." << endl << endl; } else if((computer == 1) && (input == 0)) { cout << "지셨습니다." << endl << endl; } else if((computer == 2) && (input == 0)) { cout << "이기셨습니다." << endl << endl; } else if((computer == 2) && (input == 1)) { cout << "지셨습니다." << endl << endl; } } }
프로그램 실행화면
가위 바위 보 게임이다. 사용자로부터 0 ~ 3의 숫자를 입력받는다. 0은 가위, 1은 바위, 2는 보, 3은 종료이다.
3을 입력할 때까지 계속 가위 바위 보만을 하는 프로그램이다. 여기서 필요한 것이 난수이다. 컴퓨터가 알아서 0~2의 숫자를 선택하도록 해야한다.
이때 많이 사용하는 것이 rand()이다. 랜덤한수는 난수를 발생해준다. rand()함수만을 사용하게 되면 프로그램을 종료하고 다시 실행했을 때 같은 패턴으로 난수가 발생하기 때문에 srand((int)time(NULL)); 이 녀석을 꼭 추가해 주어야만한다.
현재 시간을 seed값으로 주어 프로그램을 종료한 후 다시 실행해도 같은 패턴으로 난수가 발생하지 않는다.