【发布时间】:2015-12-24 19:30:51
【问题描述】:
我正在尝试编写一个程序,让计算机尝试猜测用户选择的数字(1 - 100)。我已经写出了大部分程序,并且还制作了一个随机数生成器。我现在唯一需要的是一种基于用户输入的 HIGH 或 LOW 在我的程序中实现二进制搜索算法的方法。我已经阅读了一些关于二进制搜索算法的内容,但我不确定如何在我的程序中使用它。有人能指出我正确的方向吗?
第 34 行和第 42 行在应该有函数的地方有一个空白。这就是我想在我的程序中输入某种可以实现二进制搜索算法的方程的地方。
以下是我现在的代码:
#include <iostream>
#include <ctime>//A user stated that using this piece of code would make a true randomization process.
#include <cstdlib>
#include <windows.h>
using namespace std;
int main()
{
int highLow;
int yesNo;
int ranNum;
srand( time(0));
ranNum = rand() % 100 + 1;
cout << "Please think of a number between 1-100. I'm going to try to guess it.\n";
_sleep(3000);
cout << "I'm going to make a guess. Is it "<< ranNum <<" (1 for yes and 2 for no)?\n";
cin >> yesNo;
while (yesNo == 2)
{
cout << "Please tell me if my guess was higher or lower than your number\n";
cout << "by inputting 3 for HIGHER and 4 for LOWER.\n";
cin >> highLow;
if (highLow == 3)
{
cout << "Okay, so my guess was higher than your number. Let me try again.\n";
_sleep (1500);
cout << "Was your number " << <<"? If yes, input 1. If not, input 2.\n";// I would like to find a way to implement the
//binary search algorithm in this line of code.
cin >> yesNo;
}
if (highLow == 4)
{
cout << "Okay, so my guess was lower than your number. Let me try again.\n";
_sleep (1500);
cout << "Was your number " << <<"? If yes, input 1. If not, input 2.\n";// I would like to find a way to implement the
//binary search algorithm in this line of code.
cin >> yesNo;
}
}
if (yesNo == 1)
{
cout << "My guess was correct!\n";
}
}
【问题讨论】:
-
你有二分查找功能吗?如果没有,您应该做的第一件事是创建一个并在硬编码输入上对其进行测试。一旦测试正确,您就可以将其应用到更大的程序中。
-
欢迎来到 StackOverflow。虽然您的问题无疑很有趣,但 SO 不是代码编写服务。例如,您可以询问现有但有缺陷的二分搜索算法、各种损坏的 API,但不能询问容易引起争论或长时间讨论的问题。 SO 也不是博客。
标签: c++ algorithm random binary-search