Archived

This topic is now archived and is closed to further replies.

e4

C++ random nubers

Recommended Posts

e4    122
This is probably trivial, but does anyone know how to generate a random number in C++? I #included the cstdlib and called the random function like int x; x = random(100); cout << "Number is " << x << endl; and all it said was random was an undeclared identifier. WTF! Help would be greatly appreciated.

Share this post


Link to post
Share on other sites
e4    122
That helped, but now when I execute my number is 41 every time!


Here is my program:

#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{

cout << "Your number is " << rand() % 100 << "!" << endl;
cout << endl;


return 0;
}

What i''m trying to do is generate a random number between 0 and 100. I also just tried << rand() << and same thing: 41.




Share this post


Link to post
Share on other sites
ZealousElixir    256
Tried seeding?

srand((unsigned)time(0)); // put me at the top.

EDIT : To clarify, only run that line once (i.e. put it right at the top of main(), outside of any loops, and before any rand() calls.) Also notice that you'll need to include ctime.

[edited by - zealouselixir on October 2, 2002 9:40:34 PM]

Share this post


Link to post
Share on other sites
e4    122
int main()
{
srand((unsigned)time_t(0));
int x = rand();

cout << "Your number is " << x << endl;
cout << endl;


return 0;
}

now it is 38 every time.

Share this post


Link to post
Share on other sites
e4    122
I got it to work!

// Pre: #include <ctime>
int main()
{
srand((unsigned)time(0));
int x = rand() % 100;

cout << "Your number is " << x << endl;
cout << endl;


return 0;
}

Thanks for all the help peoplez.

Edit: Though I have no clue in the world how or why it works, much less what the 'ctime' class is. Anywhere I can find out more about this?

[edited by - e4 on October 2, 2002 9:48:46 PM]

Share this post


Link to post
Share on other sites
ZealousElixir    256
quote:
Original post by e4
Edit: Though I have no clue in the world how or why it works, much less what the 'ctime' class is.

Not a class; it's a header. It just contains data types and functions for dealing with time, namely the system time.
EDIT: Now I guess I get what you're asking. Let's say this: we use the time function to get a seemingly random number (i.e. when passed to the seeding function, it causes pseudochaotic behavior and it changes often) to "seed" our RNG with, because computers can't just pull random numbers out of their patooties (yes, that IS a technical term). Basically, it sets an initial value for the random number, and the sequence generated is dependent on this value. Because it changes often, you have a greater chance of geting a "more random" series.
quote:
Anywhere I can find out more about this?

MSDN owns you.

[edited by - zealouselixir on October 2, 2002 11:54:01 PM]

Share this post


Link to post
Share on other sites