본문 바로가기
C++

C++ 예제: Up/Down 게임(22.04.07)

by Luden59 2022. 4. 7.
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    int num;
    srand(time(0));
    int answer = rand() % 100;
    bool flag = false;

    for (int i = 0; i < 5;i++) {
        cout << "숫자를 맞춰보세요(" << 5 - i << "): ";
        cin >> num;
        if (num == answer) {
            cout << "정답!" << endl;
            flag = true;
            break;
        }
        else if (num > answer) {
            cout << "Down!" << endl;
        }
        else {
            cout << "Up!" << endl;
        }
    }

    if(!flag)
        cout << "실패! 정답은 " << answer << "였습니다." << endl;
}
  • <ctime>: 시간 관련 라이브러리
  • rand(): 랜덤 수 생성
  • srand(time(0)): 시간에 따라 랜덤 수 생성하도록 설정