2011-09-29 66 views
4

我剛剛完成了一個掃雷類型遊戲的編碼,除了每次運行應用程序時它都會產生相同的數字(我跑了3次不同的時間,將輸出保存到3個文本文件並使用diff命令Linux,它沒有發現任何差異)。它的種子編號爲time(NULL),所以每次都會改變,對吧?程序在每次運行時都會生成相同的隨機數字?

這裏是我的代碼:

的main.cpp

#include <iostream> 
#include <cstdlib> 
#include <time.h> 
#include <string> 
#include "Minesweeper/box.h" 
#include <cstdio> 

int main(int argc, char** argv){ 
using namespace std; 
bool gameOver = false; 
int x, y, score = 0; 
const int HEIGHT = 10; 
const int WIDTH = 10; 
unsigned int Time = time(0); 

cout << "Welcome to Minesweeper. " << endl; 


//setup grid 
Box grid[10][10]; 

for(int i = 0; i < WIDTH; i++) 
for(int n = 0; n < HEIGHT; n++){ 
    unsigned int value = rand() %100 + 1; 
    cout << value << endl; 
    if(value <= 38){ 
grid[i][n].setFill(MINE); 
//cout << i << "," << n << " is mined." << endl; 
    } 
    else 
grid[i][n].setFill(EMPTY); 
} 

for(int r = 0; r < WIDTH; r++) 
for(int l = 0; l < HEIGHT; l++) 
    if(grid[r][l].getFill() == EMPTY) 
cout << r << "," << l << " - EMPTY." << endl; 
    else if (grid[r][l].getFill() == MINE) 
cout << r << "," << l << " - MINE." << endl; 

while(!gameOver){ 
cout << "Enter coordinates (x,y): "; 
scanf("%i,%i",&x,&y); 
if(grid[x][y].getFill() == MINE) 
    gameOver = true; 
else{ 
    cout << "Good job! (You chose " << x << "," << y << ")" << endl; 
    score++; 
} 
} 

cout << "You hit a mine! Game over!" << endl; 
cout << "Final score: " << score << endl; 
getchar(); 

return EXIT_SUCCESS; 
} 

回答

8

它是由時間(NULL)

種子如果是,我無法看到它。事實上,在你的代碼中搜索它什麼都不會返回。默認的行爲,如果你沒有明確的種子,是一樣的,如果你已經與值1

你需要明確說明像播種那樣:在main開始

srand (time (NULL)); 

在某處(並確保你這樣做一次和一次)。

雖然請記住,這使得它依賴於當前的時間 - 如果你在同一秒內開始多個工作(或者你的時間分辨率是什麼),它們將以相同的種子開始。

從C標準(在其C++是基於這些兼容性功能):

srand函數使用的參數作爲僞隨機數的一個新序列的種子,以通過後續調用返回蘭特。如果srand然後用相同的種子值調用,則應重複僞隨機數的序列。如果在對srand進行任何調用之前調用rand,則應當生成與srand首次調用時種子值爲1時相同的序列。

+0

謝謝,那是我的一個愚蠢的錯誤。 – airplaneman19

+1

如果OP提交批處理作業,那麼這也可能會重複。在這種情況下,多個作業同時啓動。 – jww

+0

好點,@jww,我會添加一個註釋來達到這個效果。 – paxdiablo

1

您需要種子隨機數發生器。在開始時致電srand()

1

要讓別人添加答案,您可以使用Mersenne Twister算法,該算法是C++ 11庫的一部分。它很快成爲許多常用軟件生成隨機數的標準。

例如,這是我寫的功能,這是我經常使用我的其他代碼生成隨機數:

std::vector<double> mersennetwister(const int& My,const int& Mz, 
const int& Ny,const int& Nz) 
{ 
int ysize = (My + 2*Ny + 1); 
int zsize = (Mz + 2*Nz + 1); 
int matsize = ysize*zsize; 
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); 
// Seeding the generator with the system time 
std::mt19937_64 generator (seed); 
// Calling the Mersenne-Twister Generator in C++11 
std::uniform_real_distribution<double> distribution(0,1); 
// Specifying the type of distribution you want 
std::vector<double> randarray(matsize,0); 
// Saving random numbers to an array 
for (int i=0;i<matsize;++i) 
{ 
    randarray[i] = distribution(generator); // Generates random numbers fitting the 
    // Distribution specified earlier 
} 
return(randarray); 
} 

底線:C++ 11有一些優秀的功能進行數值運算,它會對他們進行調查是個好主意。至於Mersenne Twister,http://en.wikipedia.org/wiki/Mersenne_twister

相關問題