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)



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;

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

    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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.