2017-04-25 79 views
0

我正在尝试一个我发现的猜谜游戏,似乎无论我选择什么,它都会说我选择的数字少于或多于。我想用二分查找来实现它,但不知道如何做到这一点。我怎样才能做到这一点?在C++上尝试数字猜谜游戏

代码:

#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; 
} 
+1

所以,你想编码自动猜测的数字,或者你想他的用户猜测数字? – NathanOliver

+0

我希望用户猜测它,例如,秘密数字是58,用户不断尝试输入一些数字,如果他得到它,他会,如果没有,程序继续询问。我使用rand()使游戏更有趣,因为它总是生成一个随机数。 – Uxellodunon

+3

如果用户是进行搜索的用户,您要实现二分搜索究竟是什么? –

回答

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; 
} 
+0

我的理解是用户正在猜测计算机的号码。以你为例,计算机正在猜测一个随机数。 –

+0

@ThomasMatthews downvoting回答之前, 在OP 中阅读此行“我想用二分查找来实现它,但不知道如何做到这一点,我怎么能做到这一点? 最有可能实现二进制搜索意味着计算机通过执行二进制搜索找到随机数, 但我可以再次错误 –

+0

在OP的评论中读取此行:*“我希望用户猜测它,例如秘密数字是58,用户不断尝试输入一些数字,如果他得到它,他会,如果没有,程序继续询问。“* –

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; 
} 

后面每次Finnally我认为这是一个概念的错误理解比赛,因为当它说“对不起,再试一次,它比秘密大数!”键盘输入的数字是指秘密数字较大。我真的希望这一行能够为你清楚这些事情。问候