在C ++上尝试一个猜数游戏

时间:2017-04-25 14:41:17

标签: c++ binary-search

我正在尝试一个我发现的数字猜谜游戏,似乎无论我选择什么,它一直在说我选择的数字小于或超过。我想用二进制搜索实现它,但不知道如何做到这一点。我怎样才能实现呢?

代码:

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

using namespace std;

int main() {
      srand(time(0));
      int number;
      number = rand() % 100 + 1;
      int guess;
      do {
            cout << "Enter a number of your choice b/w 1-100: ";
            cin >> guess;
            if (guess < number)
                  cout << "Sorry, try again, it's smaller than the secret number!" << endl;
            else if (guess > number)
                  cout << "Sorry, try again, it's bigger than the secret number!" << endl;
            else
                  cout << "The number is correct! Congratulations!" << endl;
      } while (guess != number);
      system("PAUSE");
      return 0;
}

2 个答案:

答案 0 :(得分:1)

这应该做这件事

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;
int guessNum(int lb,int ub,int number){
    int lowerBound=lb,upperBound=ub;
    int guess = (lowerBound+upperBound)/2;
    if (number>guess){
        lowerBound = guess;
        guessNum(lowerBound,upperBound,number);
    }
    else if(number < guess){
        upperBound=guess;
        guessNum(lowerBound,upperBound,number);
    }

    else
        return guess;
}

int main() {
    srand(time(NULL));
    int number;
    number = rand() % 100 + 1;
    int guess;

          std::cout<<number << " = " <<guessNum(1,100,number);


    return 0;
}

答案 1 :(得分:0)

了解游戏

软件随机选择0-100之间的数字,你需要找到它吗? ,该软件给了你一些线索,但你从来没有找到这个数字。那么,解决方案是什么?

作弊游戏

当事情出错时,我宁愿明白。因此,向软件询问号码,您将知道哪个号码。每当我需要知道幕后发生的事情时,我就会这样做

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

using namespace std;

int main() {
      srand(time(0));
      int number;
      number = rand() % 100 + 1;
      int guess;
      do {
            cout << "Enter a number of your choice b/w 1-100: ";
            cin >> guess;
            // with this line ↓ you could see what is happen
            cout << "Your number is " << guess << " and the secret number is " << number << endl;
            if (guess < number)
                  cout << "Sorry, try again, it's smaller than the secret number!" << endl;
            else if (guess > number)
                  cout << "Sorry, try again, it's bigger than the secret number!" << endl;
            else
                  cout << "The number is correct! Congratulations!" << endl;
      } while (guess != number);
      system("PAUSE");
      return 0;
}

最后我认为理解游戏是一个概念错误,因为当它说“抱歉,再试一次,它比秘密号码大!”它是指您输入的数字键盘比密码大。我真的希望这条线能为你澄清一切。此致