2010-11-12 116 views
0

我正在嘗試編寫一個程序,該程序使用種子生成僞隨機數。但是,我遇到了問題。srand(),C++的問題

我得到這個錯誤

39 C:\Dev-Cpp\srand_prg.cpp void value not ignored as it ought to be 

使用此代碼

#include <iostream> 
#include <iomanip> 
#include <sstream> 
#include <limits> 
#include <stdio.h> 

using namespace std ; 

int main(){ 
    int rand_int; 
    string close ; 

    close == "y" ; 

    cout << endl << endl ; 
    cout << "\t ___________________________________" << endl ; 
    cout << "\t|         |" << endl ; 
    cout << "\t| Pseudorandom Number Game!  |" << endl ; 
    cout << "\t|___________________________________|" << endl ; 
    cout << endl << endl ; 

    while (close != "y"){ 

     rand_int = srand(9); 
     cout << rand_int << endl ; 

     cout << " Do you wish to exit the program? [y/n]  " ; 
     cin >> close ; } 

} 
+3

下面很多很好的答案的。爲了將來的參考,編譯器消息「void value not ignored as it should be」告訴你:「你正在使用定義爲不返回任何東西的函數的結果('void')」。這通常意味着你應該檢查關於函數應該如何使用的文檔,因爲你正在嘗試的是不正確的。 – 2010-11-12 04:12:25

回答

7

srand不返回一個隨機數,它只是補種的隨機數發生器。之後撥打rand即可獲得一個號碼:

srand(9); 
rand_int = rand(); 
+4

,只能調用一次srand – 2010-11-12 09:24:56

3

這樣稱呼它。

srand(9); 
rand_int = rand(); 
4

srand()函數生成一個種子(其是用於初始化隨機數生成器的數量),並且必須被調用每個進程一次。 rand()是你正在尋找的功能。

如果你不知道該選擇什麼樣的種子,使用當前時間:

srand(static_cast<unsigned int>(time(0))); // include <ctime> to use time() 
1

函數srand返回void功能,並且不返回值。

Here你可以看到更多關於它的內容。你只需要調用srand(9),然後獲得rand()的值,就像J-16 SDiZ指出的那樣,誰將會爲此贊成:)

1

你錯誤地使用了srand,特別的功能是設置種子以便稍後調用rand

基本思想是用一個不確定的種子調用srand一次,然後連續調用rand得到一個數字序列。例如:

srand (time (0)); 
for (int i = 0; i < 10; i++) 
    cout << (rand() % 10); 

這應該給你一些0和9之間的隨機數。

除非您正在測試,否則您通常不會將種子設置爲特定值,或者您出於某種其他原因需要相同的數字序列。您在每次撥打rand之前也不要設置種子,因爲您可能會重複獲得相同的號碼。

所以你特別while循環會更喜歡:

srand (9); // or use time(0) for different sequence each time. 
while (close != "y") { // for 1 thru 9 inclusive. 
    rand_int = rand() % 9 + 1; 
    cout << rand_int << endl; 

    cout << "Do you wish to exit the program? [y/n]? "; 
    cin >> close; 
}