0

Hi, I've been looking for a while for things that would give me random numbers under a value that I can specify (for me it's 5).

I've seen rand(); and srand(); . I also know that srand() is the seed and rand() is the random number itself.

Even the example programs don't work as expected (they don't return different numbers on each execution, I need it to return different numbers each time)

Thanks,

JT

4
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by pseudorandom21
0

Your probably using it wrong. Try this :

#include <ctime>
#include <iostream>
using namespace std;

int main(){
 srand( time(0) ); //seed with different number each execution
 for(int i = 0; i < 10; ++i) cout << rand() << endl;
0

The seed needs to be different each time for the sequence to be different. Most people prefer to seed based on the current time:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    std::srand((unsigned)std::time(0));

    for (int i = 0; i < 10; i++)
        std::cout<< std::rand() % 5 <<'\n';
}

That's not strictly portable, but I have yet to see it not work.

0

Typically you will get bad results if you call srand() too often. I've seen it used in a loop or a function right before every call to rand(). Try calling it once for the lifetime of the program.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.