我正在嘗試一個我發現的猜謎遊戲,似乎無論我選擇什麼,它都會說我選擇的數字少於或多於。我想用二分查找來實現它,但不知道如何做到這一點。我怎樣才能做到這一點?在C++上嘗試數字猜謎遊戲
代碼:
#include <cstdlib>
#include <time.h>
#include <iostream>
using namespace std;
int main() {
srand(time(0));
int number;
number = rand() % 100 + 1;
int guess;
do {
cout << "Enter a number of your choice b/w 1-100: ";
cin >> guess;
if (guess < number)
cout << "Sorry, try again, it's smaller than the secret number!" << endl;
else if (guess > number)
cout << "Sorry, try again, it's bigger than the secret number!" << endl;
else
cout << "The number is correct! Congratulations!" << endl;
} while (guess != number);
system("PAUSE");
return 0;
}
所以,你想編碼自動猜測的數字,或者你想他的用戶猜測數字? – NathanOliver
我希望用戶猜測它,例如,祕密數字是58,用戶不斷嘗試輸入一些數字,如果他得到它,他會,如果沒有,程序繼續詢問。我使用rand()使遊戲更有趣,因爲它總是生成一個隨機數。 – Uxellodunon
如果用戶是進行搜索的用戶,您要實現二分搜索究竟是什麼? –