猜一个秘密号码(计算机与计算机) - AI

时间:2015-05-28 01:59:15

标签: c++ numbers artificial-intelligence

我的代码猜测一个秘密号码有问题。我想制作游戏只是计算机猜测和答案。我试着编写代码,但结果是无限循环。

这是我的代码:

#include <cstdlib>
#include <time.h>
#include <iostream>

using namespace std;

int main() {
  int lowest = 0;
  int highest = 9;
  srand(time(0));
  int number;
  number = rand() % 9+1;
  int guess;
  guess = rand() % 9+1;
  do {
      if (number){
        switch(number)
               {
                          case 1:
                                 if(guess>lowest)
                                lowest=guess;
                                do {
                                   guess=rand()%9 +1;
                                   }while(guess<lowest || guess>highest);
                               break;
                           case 2:
                                if(guess<highest)
                               highest=guess;
                               do  {
                                   guess=rand()%9 +1;
                                   }while(guess<lowest || guess>highest);
                                break;
                            case 3:
                                  cout<<"\n\n\aHA! I got it right"<< endl;
                                 break;
               }

        if (guess < number){
              cout << "Your guess is less than secret number"<<endl ;
              }
        else if (guess > number){
              cout << "Your guess is high than secret number"<<endl ;
              }
        else
              cout << "Your guess is right!" << endl;

      }
  } while (guess != number);

  return 0;
}

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我认为您对switch语句的工作原理感到困惑。如上所述,您的代码会查看number,如果数字为1(在这种情况下执行情况1),或number2或{{ 1}}。如果3不是这些选项之一,则它不执行任何操作。我怀疑你想要用number块替换开关。您似乎正在努力解决基本语法,特别是控制流程。要获得更多信息,请查看本网站的第5章:http://www.learncpp.com/。我认为这可以帮助您更好地理解您的代码正在做什么。