2017-04-25 23 views
0

我正在嘗試一個我發現的猜謎遊戲,似乎無論我選擇什麼,它都會說我選擇的數字少於或多於。我想用二分查找來實現它,但不知道如何做到這一點。我怎樣才能做到這一點?在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; 
} 
+1

所以,你想編碼自動猜測的數字,或者你想他的用戶猜測數字? – NathanOliver

+0

我希望用戶猜測它,例如,祕密數字是58,用戶不斷嘗試輸入一些數字,如果他得到它,他會,如果沒有,程序繼續詢問。我使用rand()使遊戲更有趣,因爲它總是生成一個隨機數。 – Uxellodunon

+3

如果用戶是進行搜索的用戶,您要實現二分搜索究竟是什麼? –

回答

1

這應該做這個事情

#include <cstdlib> 
#include <ctime> 
#include <iostream> 

using namespace std; 
int guessNum(int lb,int ub,int number){ 
    int lowerBound=lb,upperBound=ub; 
    int guess = (lowerBound+upperBound)/2; 
    if (number>guess){ 
     lowerBound = guess; 
     guessNum(lowerBound,upperBound,number); 
    } 
    else if(number < guess){ 
     upperBound=guess; 
     guessNum(lowerBound,upperBound,number); 
    } 

    else 
     return guess; 
} 

int main() { 
    srand(time(NULL)); 
    int number; 
    number = rand() % 100 + 1; 
    int guess; 

      std::cout<<number << " = " <<guessNum(1,100,number); 


    return 0; 
} 
+0

我的理解是用戶正在猜測計算機的號碼。以你爲例,計算機正在猜測一個隨機數。 –

+0

@ThomasMatthews downvoting回答之前, 在OP 中閱讀此行「我想用二分查找來實現它,但不知道如何做到這一點,我怎麼能做到這一點? 最有可能實現二進制搜索意味着計算機通過執行二進制搜索找到隨機數, 但我可以再次錯誤 –

+0

在OP的評論中讀取此行:*「我希望用戶猜測它,例如祕密數字是58,用戶不斷嘗試輸入一些數字,如果他得到它,他會,如果沒有,程序繼續詢問。「* –

0

瞭解遊戲

軟件隨機選擇0-100之間的數字,你需要找到它¿對? ,該軟件給了你一些線索,但你從來沒有找到數字。那麼,解決方案是什麼?

作弊遊戲

當事情出錯時,我更願意說清楚。所以,向軟件詢問號碼,你就會知道哪個號碼。我這樣做,我需要知道什麼是發生場景

#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; 
      // with this line ↓ you could see what is happen 
      cout << "Your number is " << guess << " and the secret number is " << number << endl; 
      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; 
} 

後面每次Finnally我認爲這是一個概念的錯誤理解比賽,因爲當它說「對不起,再試一次,它比祕密大數!」鍵盤輸入的數字是指祕密數字較大。我真的希望這一行能夠爲你清楚這些事情。問候