# random number per milisecond

• 06-05-2004
Xarr
random number per milisecond
I've looked at this post
http://cboard.cprogramming.com/cplusplus-programming/53242-random-number.html

and I checked preludes random number generator, but can't you make it shift to a new number every half or whole milisecond?

It would be better since it is, well, really slow for a game of dice.
• 06-05-2004
Salem
Yeah, stop calling
srand( time(0) );
each time you want a new rand() value

You only need to call this ONCE per program run.
• 06-05-2004
Thantos
every call to rand() will give you another number in the sequence. The time is only a factor when seeding the generator.

Edit: Dang beaten
• 06-05-2004
Xarr
Oh yeah almost forgot

How would I put the random number into a variable instead of outputting it?

The class std isn't defined in the code...
• 06-05-2004
Thantos
std is the namespace.

to put it in a variable you would just use it like any other return value from a function.

int x = rand();
• 06-05-2004
Xarr
but it isn't the rand() function i'm talking about it's the one prelude wrote. The 5th reply here: http://cboard.cprogramming.com/cplusplus-programming/53242-random-number.html

there (edit: she) defines the implementation thing and the fucntion random().

What I would like to know is (apart from how to change it's shifting speed): how to save the number that the for loop makes into an variable "x" instead of cout'ing it
• 06-05-2004
Thantos
Its still a function. It follows the exact same rules as any other return value.

BTW Prelude is a she.
• 06-05-2004
swoopy
Code:

```  int x;   std::srand(time_seed());   for (int i = 0; i < 10; i++) {     x = static_cast<int>(random() * 10);```
For dice, you'd use:
Code:

```  int x;   std::srand(time_seed());   for (int i = 0; i < 10; i++) {     x = static_cast<int>(random() * 6);```
This will give an int between 0 and 5, representing one die.
• 06-06-2004
Prelude
>This will give an int between 0 and 5, representing one die.
A six sided die is the most common, but certainly not the only kind available. ;) If I were to write a simple die thrower then I would include the number of sides as an argument:
Code:

```class diemension_error: public invalid_argument { public:   diemension_error(const string& msg)     : invalid_argument(msg)   {} }; int die_toss(   int sides   ) {   if (sides < 4) {     throw diemension_error("3-D die only please"); // ;-)   }   return static_cast<int>(random() * sides); }```
• 06-07-2004
swoopy
>class diemension_error: public invalid_argument {

DIEmension ... that's a good one Prelude, haha. ;)

That's some neat code. I'm going to try running it. Is invalid_argument in the std library?
• 06-08-2004
Prelude
>Is invalid_argument in the std library?
It is indeed. Be sure to include <stdexcept> though.