2017-01-24 6 views
-7
#include<iostream> 
#include<ctime> 
#include<cstdlib> 

using namespace std; 

int main(){ 
int gnumber, rnumber; 
    char choice; 
    int tries; 

    do { 
    cout << "Welcome to the Number Guessing Game!" << endl; 
    cout << endl; // breakline 
    cout << "How many tries: "; 
    cin >> tries; 
    cout << endl; 

    while (tries > 0){ 

    srand(time(NULL)); 
    rnumber = rand() % 99; 

    cout <<"Enter an integer greater than or equal to 0 and less than 100:"; 
    cin >> gnumber; 
    system("cls"); 

    if (tries != 1){ 
     if (gnumber < 100 && gnumber >= 0){ 

      if (gnumber == rnumber){ 
      cout << "Congratulations! You've guessed the number." << endl; 
      tries--; 
      cout << "Remaining tries: " << tries << endl; 
      } 

      else if (gnumber > rnumber){ 
       cout << "Your guess is higher than the number." << endl; 
       tries--; 
       cout << " Guess Again!" << endl; 
       cout << "Remaining tries: " << tries << endl; 
      } 
      else{ 
       cout << "Your guess is lower than the number." << endl; 
       tries--; 
       cout << " Guess Again!" << endl; 
       cout << "Remaining tries: " << tries << endl; 
      } 
     } 
     else 
     cout << "Must greater or equal to 0 and lesser than 100!" << endl; 
    } 
    else 
    { 
     cout << "Game over!" <<" The number is: " << rnumber << endl; 
     cout << "Play Again? (Y/N)" << endl; 
     cin >> choice; 
     system("cls"); 

    } 

    } 
    }while(choice == 'Y' || choice == 'y'); // 

    system("pause"); 
    return 0; 
    } 

"N '또는'n '을 입력하면 루프를 멈추게됩니다. 그리고 'Y'또는 'y'를 입력하더라도 얼마나 많은 시도가 필요한지 묻지 않습니다. 대신 입력 할 정수를 직접 묻습니다. 문제를 이해하기 위해 코드를 복사하고 컴파일하십시오. 도와주세요.C++ While 루프 조건이 작동하지 않습니다.

PS :이

+0

디버거를 사용하여 코드를 실행 해 보셨습니까? –

+1

표시된 코드에서 "Y", "y", "N"또는 "n"에 대한 응답으로 무엇이든 할 수있는 좋은 방법이 될 것입니다. 귀하의 문제는 귀하의 컴퓨터가 당신이하고 싶은 것을하지 않고 귀하가하는 일만 수행한다는 것입니다. –

+0

실제로는 'Y'또는 'y'가 아닌 'Y'또는 'y'가 선택 사항이 char로 선언되어 'Y'또는 'y'가 문자 Y 또는 y와 같기 때문입니다. – cringyfudge420

답변

0

당신은 그래서 tries을 감소하지 않는 사용은 다른 한 이외의 값을 입력하면 귀하의 내부 루프에서 버그 ... 내가 곧 길이로 만드는 있어요 추측 프로그램입니다 걸려 넘어지기 :

else 
    { 
     cout << "Game over!" <<" The number is: " << rnumber << endl; 
     cout << "Play Again? (Y/N)" << endl; 
     cin >> choice; 
     system("cls"); 
     tries--; // add this 
    } 
+0

Y 또는 y를 선택 사항으로 입력 했더라도 프로그램이 종료됩니다. – cringyfudge420

+0

나는 그것을 시도하고 그것은 잘 작동 – Raindrop7

+0

시도의 처음 번호가 0으로 간 후 얼마나 많은 시도를 다시 묻는가? – cringyfudge420