# Thread: rand() gives only one number...

1. ## rand() gives only one number...

Hey.
Im a new C++ programmer and having trouble using rand() in programs.
the only number rand returns is 41.
Is there anything I can do to make it generate other numbers?
Or is there any better generators?
Thank you for reading this thread and have a good day =).

2. How are you using it? Are you calling srand() first?
Post an example.

3. >> Is there anything I can do to make it generate other numbers?

Of course not. Why would you want any other number? How useful would that be?

>> Or is there any better generators?

The implementation of rand is not dictated by the standard, so really just depends on how it is implemented on your platform.

>> Im a new C++ programmer and having trouble using rand() in programs.

You need to seed your generator before you first use it. Look up srand.

4. Okay i have looked srand up.
But i still don't understand its syntax :S
srand(time(NULL))

5. That has nothing to do with it's syntax, but one particular usage. You should probably get a hold of some decent CRT API documentation. Here's what mine says:

stdlib.h

Category

Math Routines

Syntax

#include <stdlib.h>
void srand(unsigned seed);

Description

Initializes random number generator.

The random number generator is reinitialized by calling srand with an argument value of 1. It can be set to a new starting point by calling srand with a given seed number.

Return Value

None.
Exercise: Now look up the documentation for the 'time' function. Things will be much clearer then.

6. Remember that the seed must be initialized with a unique number, because a randomizer is basically just an algorithm applied to a unique number.
This is why we see this particular line of code very often.
Once you read the documentation on time, it should be clear.

7. okay. can you give me a example of rand() where it gives a totally random number and im not sure
what time has to do with random numbers.

8. Code:
```int main()
{
std::srand( (unsigned int)std::time(NULL) );
for (int i = 0; i < 10; i++)
std::cout << std::rand() << std::endl;
}```
It's still your job to figure out how this works.

9. >> im not sure what time has to do with random numbers.

Random number generators are generally not really random, but fully deterministic and thus "psuedo-random". That simply means that if you give a particular implementation the value 3114 it will generate the same sequence of numbers everytime. Naturally, you'll probably want to get different values in most cases, so you need a function that can produce an ever-changing flow of numbers, and the 'time' function is one such source. But there are other possibilities, of course. You could access the CPU temperature, for instance, and produce a seed from that.

10. Ahh i get it now, Thanks a lot!