我正在做一個小數目的猜測程序(把它叫做我製作真實遊戲的第一步)。它有兩種主要的模式,讓用戶猜測電腦的號碼(我很容易)和用戶選擇號碼的地方,而電腦必須得到它。兩種模式都可以在用戶輸入「高」或「低」或「確切」的某種形式下工作,以接近答案。什麼使這個二進制搜索接近最大範圍?
但我在使用二分查找功能讓計算機找到用戶選擇的號碼時遇到了問題。這一切都運行,我可以進入模式,但每當我按下輸入它只是進入最大範圍(範圍從1-100)。我擔心在二分查找中存在一些小的邏輯故障,但是從我所能看到的情況來看。
在我寫這篇文章的時候,我發現了一個新的bug。如果我輸入猜測並猜測計算機的號碼並再次輸入猜測,則只需循環,直到按下「選擇」或「退出」。我還沒有看過它。但任何意見將不勝感激。
我自己的目標是至少進入更復雜的基於文本的遊戲邏輯或實際上從物理圖形開始。
計劃本身....
#include <iostream>
#include <string>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(){
int i, randomNumber, guess
, computerGuess, middle;
int last = 100;
int first =1;
string choice, answer;
srand(time(NULL));
randomNumber= (rand()% last + first);
//Loop entire program until QUIT is specified.
do{
i = 0;
cout << "\n\nGood day, I would like to play";
cout << " a number guessing game" << endl;
cout << "Type QUIT to quit the program \n" << endl;
cout << "Who would you like to be?" << endl;
cout << "Guesser or picker?" << endl;
getline(cin,choice);
//Changes the string choice to uppercase
while (i<choice.size()){
choice[i] = toupper(choice[i]);
i++;
}
//initiates guess mode
if (choice.find("GUESS") != string::npos){
cout << "You picked guess." << endl;
while (guess != randomNumber){
cout << "Please guess the computer's number." << endl;
cin >> guess;
//User guesses and computer responds
if (guess == randomNumber){
cout << "\nYou guess right!\n" << endl;
} else if (guess > randomNumber){
cout << "\nToo high!\n" << endl;
} else if (guess < randomNumber){
cout << "\nToo low!\n" << endl;
} else {
cout << "ERROR" << endl;
}
}
}
//Initiates pick mode
if (choice.find("PICK") != string::npos){
cout << "\nYou want to pick the number." << endl;
cout << "Have the number in your head?"<< endl;
cout << "Alright, I'll guess.\n\n" << endl;
//start binary search
do{
middle= (last+first)/2;
cout << "Is " << middle << " the number?" << endl;
getline (cin,answer);
//changes answer to uppercase
while (i<answer.size()){
answer[i] = toupper(answer[i]);
i++;
}
//add (middle+1) to first if LOW
if (answer.find("LOW")){
first = middle +1;
}else if (answer.find("HIGH")){
//add (middle-1) to last if HIGH
last = middle -1;
}
}while (answer.find("EXACT") == string::npos);
cout << "So the number is " << middle << endl;
}
}while (choice.find("QUIT") == string::npos);
return (0);
}
嘿,感謝您的意見。更要感謝他們解釋爲什麼事情發生了。這會幫助我不要再犯同樣的錯誤。 –