Problems with srand(), C++

余生颓废 提交于 2019-12-02 11:25:19

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();

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()

call it this way.

srand(9);
rand_int = rand();

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 :)

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