# Thread: Any way to set peramiters for rand() to return?

1. ## Any way to set peramiters for rand() to return?

I'm trying to write a simple program that has the function rand() to assign a number between 1 and 100 to int x. Right now, the only way I can get this to happen, is to have the program to check x after it is set, and if it is above 100, "try again". Can I tell rand() to simply "not return above 100". It would be a 'much' more efficent technique

2. Please read the tutorials before posting!...

3. Originally Posted by ashinms
I'm trying to write a simple program that has the function rand() to assign a number between 1 and 100 to int x. Right now, the only way I can get this to happen, is to have the program to check x after it is set, and if it is above 100, "try again". Can I tell rand() to simply "not return above 100". It would be a 'much' more efficent technique
The tutorial that Sipher linked to suggests a technique that can introduce some bias, but it may still be acceptable for you. I suggest reading Prelude's article on using rand() for elaboration and alternatives.

The method that I prefer is a variant of the rejection method that you have in mind (and which Prelude mentions in her article):
Code:
```const int range_min = 1;
const int range_max = 100;
const int range_size = range_max - range_min + 1
do
{
n = rand();
}
while (n >= (RAND_MAX / range_size) * range_size);
n = n % range_size + range_min;```
If they are available to you, you can also use the pseudorandom number generator facilities from the TR1 extension to the standard library.

4. Looked for it, but couldnt find the link. thanks

Popular pages Recent additions