c++二进制搜索无论用户类型如何都会返回(find)
c++ Binary search returns (found) no matter what user types
我正在开发一款刽子手游戏,我正试图弄清楚为什么无论用户键入什么,它都会返回"That letter have been used";
这是函数定义。。。
bool binarySearch(char usedLetters[], int used, char letterToFind)
{
bool found = false;
int mid = 0, first = 0, last = used - 1;
while (!found && first <= last)
{
mid = (first + last) / 2;
if (usedLetters[mid] == letterToFind)
found = true;
else if (usedLetters[mid] > letterToFind) // works on ascending sorted collections only
last = mid - 1; // first half
else
first = mid + 1; // last half
}
if (found)
return mid;
return -1;
}
这是声明。。。
char gLetter;
int wrong = 0;
int gameStatus = 5;
int chances = 0;
int used = 0;
int letterIndex;
这是main中的函数调用。。。
while (wrong != 6) // Function to find out which hangman board to print to user
{
cout << "<<<<<<<<<< MAKE A GUESS >>>>>>>>>>n";
cout << "Guessed Letters: " << usedLetters << endl;
cout << "nEnter a letter to guess: ";
cin >> gLetter;
gLetter = toupper(gLetter);
usedLetters[used++] = gLetter;
letterIndex = binarySearch(usedLetters, used, gLetter); // Binary search for letters used
bubbleSort(usedLetters, used);
if (letterIndex == -1)
{
continue;
}
else
{
cout << "That letter has already been usedn";
}
只需要弄清楚为什么用户输入的字符总是在尚未使用时被找到。我想这是因为我声明了"int used=0",但当我将其更改为其他值时,比如26,二进制搜索不会返回任何字母。
false
为0。其他的都是true
。
bool binarySearch(char usedLetters[], int used, char letterToFind)
...
if (found)
return mid;
return -1;
仅当您在索引0处找到内容时(mid
为0),才会返回false
。
另请参阅http://ideone.com/2XU2bn
--编辑--
您表示只想知道字母是否存在,所以只需返回found
相关文章:
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ find() 在存储为变量时返回不同的值
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- find() 没有返回可以使用的 int 值,并且在编译之前给出错误
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- 由 std::find() 返回的迭代器不可取消引用
- 为什么空 unordered_map.find 不返回 end()?
- C++ std::find() 寻址返回向量的类函数时的意外行为
- std::string::find 返回错误的答案
- std::string::find 总是返回 string::npos 偶数
- GetPrivateProfileStringA 返回"The system cannot find the file specified."即使文件存在
- String.find() 在 C++ 中找不到任何内容时不会返回 -1
- 为什么要对 map::find 应用不存在的键将返回一个C++中第一个值映射大小的迭代器
- std::map中的find()函数返回一个值,尽管没有有效的键
- std :: map find()返回错误
- 自定义类对象的向量的std::find的返回值
- 哪个元素将从 std::multimap::find 返回,同样,std::multiset::find
- 使用 string::find 和 string::substr 拆分字符串的函数返回错误的标记
- c++二进制搜索无论用户类型如何都会返回(find)