c++二进制搜索无论用户类型如何都会返回(find)

c++ Binary search returns (found) no matter what user types

本文关键字:返回 find 搜索 二进制 类型 用户 c++      更新时间:2023-10-16

我正在开发一款刽子手游戏,我正试图弄清楚为什么无论用户键入什么,它都会返回"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