2017-09-17 72 views
1

我正在讀的書叫的解決方案「跳進C++」,即它要我建立一個程序,發現挑選1和100之間的數字隨機一個猜謎遊戲的解決方案,讓用戶猜猜這個數字是多少,並告訴他們他們的猜測是高,低還是正好。 基本上它要我預測下一個隨機數,但我無法想出辦法,因爲我是一個新手。C++程序找出猜謎遊戲

這是猜謎遊戲的代碼:

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

using namespace std; 

int x,y; 
int rand_range(int low, int high) 
{ 
    return rand() % (high - low) + low; 
} 

int main() 
{ 
    int seed = time(NULL); 
    srand(seed); 
    int y = rand_range(1, 100); 
    cout << "Program has picked a no. between 1 to 100... You just make a 
      guess....\n"; 
    cin >> x; 
    while(1) 
    { 
     if(x == y) 
     { 
      cout << "just right\n";return 0; 
     } 
     else if(x < y) 
     { 
     cout << "low\n";return 0; 
     } 
     else 
     { 
     cout << "high\n";return 0; 
     } 
    } 
} 

這個程序讓用戶猜1之間的數字爲100,然後檢查猜測是否爲低,高或剛剛好,但我需要一個計劃,解決上述猜測問題並猜測隨機號碼。究竟。 意思是我需要一種方法來預測下一個僞隨機數。

+2

樣品的輸入和輸出,請 –

+0

你需要解釋什麼並不完全工作(你想要什麼,你得到了什麼,而不是)。 – Drop

回答

-2

我已經編輯你的代碼。你將代碼放在一個無限循環中,但是對於每一種可能的情況你都退出循環,所以沒有一個有效的指向。相反,您應該有一個循環,一旦用戶猜到正確的輸入就結束。

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

using namespace std; 

int x,y; 
int rand_range(int low, int high) 
{ 
    return rand() % (high - low) + low; 
} 

int main() 
{ 
    int seed = time(NULL); 
    srand(seed); 
    int y = rand_range(1, 100); 
    cout << "Program has picked a no. between 1 to 100... " 
     << "You just make a guess....\n"; 
    cin >> x; 
    while(x != y) { 
     if(x < y) 
      cout << "low\n"; 

     else 
      cout << "high\n"; 

     cin >> x; 
    } 

    cout << "just right\n"; 
    return 0; 

} 
+1

這假設如何工作?您只需輸入一次。如果數字與y不匹配,您的程序將在無限的時間內連續打印「高」或「低」。 –

+1

哎呀抱歉,我錯過了。修復了while循環,因此它始終從命令行獲取參數。 –

1

您的代碼有一些基本錯誤。首先你需要循環輸入。其次,你在所有的條件下返回。這就是爲什麼你的代碼試圖只匹配一次目標。而且你必須在循環中進行輸入,因爲你想嘗試猜測數字。爲此,你必須每次輸入一次。我已經稍微編輯了你的代碼。請檢查以下代碼 -

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

using namespace std; 

int x,y; 
int rand_range(int low, int high) 
{ 
    return rand() % (high - low) + low; 
} 

int main() 
{ 
    int seed = time(NULL); 
    srand(seed); 
    int y = rand_range(1, 100); 
    cout << "Program has picked a no. between 1 to 100... You just make a guess....\n"; 

    while(1) 
    { 
    cin >> x; // Now taking input in the loop 
     if(x == y) 
     { 
      cout << "just right\n";return 0; 
     } 
     else if(x < y) 
     { 
     cout << "low\n"; //omitted the return line 
     } 
     else 
     { 
     cout << "high\n"; // omitted the return line 
     } 
    } 
} 

要猜測下一個僞隨機數,您必須假定確定性算法。對於一個新手來說,問題和方式太難了,這太寬泛了。請看到這個帖子 - Is it possible to predict the next number in a number generator?