Problems with srand(), C++

风格不统一 提交于 2019-12-20 07:27:45

问题


I'm trying to write a program that generates a pseudorandom numbers using a seed. However, I'm running into problems.

I get this error

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

Using this code

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

}

回答1:


srand doesn't return a random number, it just reseeds the random number generator. Call rand afterwards to actually get a number:

srand(9);
rand_int = rand();



回答2:


srand() generates a seed (which is the number used to initialize the random number generator) and must be called once per process. rand() is the function you are looking for.

If you don't know what seed to pick, use the current time:

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



回答3:


call it this way.

srand(9);
rand_int = rand();



回答4:


srand returns void function and doesn't return a value.

Here you can see more about it. You'll just have to call srand(9) and get the value of rand() after that, like J-16 SDiZ pointed out, who will be upvoted for this :)




回答5:


You're using srand incorrectly, that particular function is for setting the seed for later calls to rand.

The basic idea is to call srand once with an indeterminate seed, then call rand continuously to get a sequence of numbers. Something like:

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

which should give you some random numbers between 0 and 9 inclusive.

You generally don't set the seed to a specific value unless you're testing or you want an identical sequence of numbers for some other reason. You also don't set the seed each time before you call rand since you're likely to get the same number repeatedly.

So your particular while loop would be more like:

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


来源:https://stackoverflow.com/questions/4161501/problems-with-srand-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!