srand

Hi everyone , so I'm new to C++ and i wrote a little code , I defined a function witch randomize some variables between two numbers everytime I call it , but even if I restart my program , it's not changing the variables value , Thanks.

1
2
3
4
 void randomize()
{
	srand(time(NULL))-rand() % 100000000000000);
}


This is the randomize function

Hi,
Too much work.

==>
1
2
3
4
void randomize()
{
	srand(static_cast<unsigned int>(time(NULL)));
}
Does that help? :)
If using rand () you need to first include these under #include <iostream>:
#include <cstdlib>
#include <ctime>

Then you need to seed it in main with:
srand (time(0));

(You only use this one time). You can also use NULL in place of 0;

Now you can call it anytime you want in your program with something like:
random_number = rand () % 8 + 1;

This makes a random number from 1-8.

There are other ways to do this using rand () but this way is the easiest. And there are other ways to do random numbers in place of rand () but this will work very well with simple games and programs.

Hope this helps.
Topic archived. No new replies allowed.