[try Beta version]
Not logged in

 
How to generate random numbers in C++?

May 9, 2013 at 6:33pm
Hi, I'm looking for a way to generate random numbers and no idea how, I've tried looking around the web but no examples seem to compile for me, it's likely to do with not having the correct libraries which no archives seem to mention. Lots of posts mention the "time" function but I've never heard of it before and it doesn't compile when I use it.

Any info on syntax to use and which libraries to include would be much appreciated. :)
Last edited on May 9, 2013 at 6:35pm
May 9, 2013 at 6:35pm
http://www.cplusplus.com/reference/cstdlib/rand/

1
2
3
4
5
6
7
8
#include <cstdlib>
#include <iostream>

int main()
{
    std::cout << std::rand();
    return 0;
}
May 9, 2013 at 7:24pm
1
2
3
4
5
6
#include <ctime>
//...
srand((int)time(0));
// random number from 1-10
x = rand() % 10 + 1; 
//... 
Last edited on May 9, 2013 at 7:25pm
May 9, 2013 at 7:28pm
But don't forget to call srand() once, near the beginning of main, to seed the random number generator. Bourgond Aries's example gives me 41 every time I run it.

See the the reference entry of rand for a more complete example.

Andy
May 9, 2013 at 8:39pm
Thanks for the replies guys, problem solved :)
Topic archived. No new replies allowed.