1

シードを使用して疑似乱数を生成するプログラムを作成しようとしています。しかし、私は問題に直面しています。

このエラーが発生します

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 ; }

}
4

5 に答える 5

8

srand乱数を返すのではなく、乱数ジェネレーターを再シードするだけです。rand後で電話して、実際に番号を取得します。

srand(9);
rand_int = rand();
于 2010-11-12T04:01:35.163 に答える
4

srand() はシード (乱数ジェネレーターの初期化に使用される数値) を生成し、プロセスごとに 1 回呼び出す必要があります。rand() は、探している関数です。

どのシードを選択すればよいかわからない場合は、現在の時刻を使用してください。

srand(static_cast<unsigned int>(time(0))); // include <ctime> to use time()
于 2010-11-12T04:01:58.483 に答える
3

このように呼びます。

srand(9);
rand_int = rand();
于 2010-11-12T04:01:52.737 に答える
2

srand間違って使用しています。その特定の関数は、後で呼び出すためのシードを設定するためのものrandです。

基本的な考え方はsrand、不確定なシードで1回呼び出し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;
}
于 2010-11-12T04:46:12.633 に答える
1

srand は void 関数を返し、値を返しません。

詳細については、こちらを参照してください。J-16 SDiZ が指摘したように、srand(9) を呼び出してから rand() の値を取得するだけで済みます。

于 2010-11-12T04:05:26.280 に答える