8강 과제인 야구게임의 코드입니다.
과제 조건이 숫자 10~19로 설정할것, 10회 이상 시도시 종료될것. 인데
배열을 통한 랜덤 셔플은 작동하는것 같지만
아래의 게임을 반복하게 하는 while (nStrike < 3 || nCount < 10) 문에서
nCount 값이 10이 넘어도 while문을 탈출하지 못하는 현상이 있습니다.
반면 nStrike 값이 3이되면 곧 바로 while문에서 탈출하는데, 어느부분에서 오류가 나오는것인지 알수가없어 질문드립니다
#include
#include
using namespace std;
int main()
{
int nUser[3];
int nRand[10];
int nStrike = 0, nBall, nOut;
int nCount;
bool bEnding = true;
srand(time(NULL));
rand();
while (bEnding) // 게임 지속 or 끝내기
{
for (int i = 0; i < 10; i++)
nRand[i] = i + 10;
for (int i = 0; i < 100; i++)
{
int nScr = rand() % 9;
int nDest = rand() % 9;
int nTemp = nRand[nScr];
nRand[nScr] = nRand[nDest];
nRand[nDest] = nTemp;
}//랜덤셔플
nCount = 0;
nStrike = nBall = nOut = 0; // 변수 초기화
while (nStrike < 3 || nCount < 10) // 게임 시작 << 이부분입니다
{
nStrike = nBall = nOut = 0;
nCount++;
cout << nCount << "회 시도" << endl;
cout << "첫번째 숫자를 입력하세요. (10~19) : ";
cin >> nUser[0];
cout << endl << "두번째 숫자를 입력하세요. (10~19) :";
cin >> nUser[1];
cout << endl << "세번재 숫자를 입력하세요. (10~19) :";
cin >> nUser[2];
cout << nRand[0]<< "." << nRand[1]<<"." << nRand[2] << endl;
for (int i = 0 ; i < 3; i++)
{
if (nUser[i] == nRand[i])
nStrike++;
else if (nUser[i] == nRand[(i + 1) % 3] || nUser[i] == nRand[(i + 2) % 3])
nBall++;
else
nOut++;
}
cout << nStrike << ":스트라이크" << endl;
cout << nBall << ":볼" << endl;
cout << nOut << ":아웃" << endl;
system("pause");
system("cls");
}
if (nStrike = 3)
{
cout << nCount << "회 만에 성공했습니다." << endl;
}
else
cout << nCount << "회를 넘어 실패했습니다." << endl;
cout << "새 게임을 시작할까요? (y/n)" << endl;
char chContinue;
cin >> chContinue;
if (chContinue == 'n')
{
bEnding = false;
cout << "게임 끝!";
}
}
}
안녕하세요 게임클래스 입니다.
while문의 경우 ()안의 조건식이 ture인 동안은 계속 루프가 진행된다는 사실은 알고 계시죠??
지금 while안에 조건을 보면 다음과 같습니다.
while (nStrike < 3 || nCount < 10) // 게임 시작 << 이부분입니다
조건식의 논리연산자가 or 이므로 둘중 하나만 true여도 계속 반복되는 구조 입니다.
아무리 nCount가 false라고 하더라도 nStrike가 true인 이상 계속 반복된다는 말이죠.
이해 안되시면 질문 주세요~
감사합니다!