用C ++创建猜谜游戏

时间:2017-02-28 02:44:06

标签: c++ while-loop

我是使用C ++编写代码并开始学习第一门课程的新手。这应该是一个非常简单的程序,目标是程序从输入流中读取一个数字而不显示它。接下来,要求用户尝试猜测数字;给他们三个猜测。当用户从未猜对时,各种输出应显示,在第一次猜测,第二次猜测和第三次猜测时正确猜测。输出应该是这样的:

I am thinking of a number between 1 and 10. 
Can you guess it within 3 guesses? 
Enter guess #1: 6 
Enter guess #2: 7 
Enter guess #3: 8 
You lose! The number was 5

I am thinking of a number between 1 and 10. 
Can you guess it within 3 guesses? 
Enter guess #1: 66 
Please try again Enter guess #1: 67 
Please try again Enter guess #1: 68 
Please try again Enter guess #1: 6 
Enter guess #2: 7 Enter guess #3: 8 
You lose! The number was 5

我遇到的问题是,如果猜测是正确还是错误,它会不断打印出来你输了!这个数字是......或者如果猜测是正确的,它会做点什么。此外,如果猜测它在1和10之外它将连续打印出来请再试一次以及你丢失的声明。这是我到目前为止的代码,我只为第一次猜测创建了代码,直到它正确执行。

非常感谢任何建议。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main () {
  int guess;
  int guess2;
  int guess3;
  int ran;
  srand(time(0));

  cout << "I am thinking of a number bewteen 1 and 10." << endl;
  cout << "Can you guess it within 3 guesses?" << endl;

  cin >> guess;
  cin >> guess2;
  cin >> guess3;

  ran = ((rand() % 9) + 1);

  cout << ran << endl; //remove***********

  cout << "Guess #1: " << guess << endl;

   while(guess < 1 || guess > 10) { 
        cout << "Please try again" << endl;

           }  
     while(guess != ran) {
        cout << "You lose!  The number was " << ran << endl;
     }

     while(guess == ran) {
        cout << "You win!  The number was " << ran << endl;

     }

  return 0;
   }

2 个答案:

答案 0 :(得分:0)

由于guessran在打印"You lose!"的循环中都没有变化,因此循环永远不会终止。我不清楚为什么这是一个循环。

答案 1 :(得分:0)

尝试使用for循环而不是3个猜测变量。另外,使用if而不是while。     int main(){

int guess, ran, i;

srand(time(0));

cout << "I am thinking of a number bewteen 1 and 10." << endl;
cout << "Can you guess it within 3 guesses?" << endl;

ran = ((rand() % 9) + 1);

cout << ran << endl; //remove***********

for(i=0;i<3;i++) 
{
 cin >> guess;
 cout << "Guess #1: " << guess << endl;

if(guess < 1 || guess > 10) 
    cout << "Please try again" << endl;

if(guess == ran) 
    break;

}

if(guess != ran)
    cout << "you lose!";
if(guess == ran)
cout << "you win!";

return 0;
}