# Thread: random number per milisecond

1. ## random number per milisecond

I've looked at this post

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.

2. Yeah, stop calling
srand( time(0) );
each time you want a new rand() value

You only need to call this ONCE per program run.

3. 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

4. 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...

5. 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();

6. 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/showthread.php?t=53242

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

7. Its still a function. It follows the exact same rules as any other return value.

BTW Prelude is a she.

8. 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.

9. >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);
}```

10. >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?

11. >Is invalid_argument in the std library?
It is indeed. Be sure to include <stdexcept> though.