我正在一個hang子手遊戲,我想弄清楚爲什麼不管用戶輸入什麼類型,它會返回「該字母已被使用\ n」;C++二進制搜索返回(找到)無論用戶類型
下面是函數定義...
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;
,這裏是主內的函數調用...
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 used\n";
}
只需要弄清爲什麼用戶輸入的字符在他們還沒有被使用時總是被找到。我認爲它是因爲我聲明「int used = 0」,但是當我將其更改爲26之類的其他內容時,二進制搜索不會返回任何字母。
小心,usedLetters沒有分配預內存和C++在涉及到時非常愚蠢:它只是在數組的末尾寫入數據。 (或者至少,我沒有看到你是如何分配它的,但[used ++]讓我很緊張 – user1582024
另外,你的binaryserach實現有一個溢出問題:'mid =(first + last)/ 2'應該是' mid = first +(last-first)/ 2' – user1582024
您正在從'bool'類型函數中返回'int mid,-1'。 – Shravan40