I would like to know if there is a library function which can generate random integers in a specified by the user field,for example [100-150]
If anyone knows please reply as soon as possible....
Printable View
I would like to know if there is a library function which can generate random integers in a specified by the user field,for example [100-150]
If anyone knows please reply as soon as possible....
Assuming you want evenly distributed numbers:
Which will return a pseudo random number in the closed interval [100, 150].Code:int void f()
{
return rand() % 51 + 100;
}
Hope this helps
PS. The initialize the pseduo random number generator see srand()
The standard C rand() function is usually not a very good random number generator. Here is a FAQ about good random number generators.
Also, using modulo generally creates a bad set of random numbers -- they end up not being very random. (The modulo operation gives extra weight to the least significant bits of a number; and the least significant bits tend to be the least random returned from PRNGs.) A better, though slower method is to do this:
Code:/* identical interface as rand(), but produces better random sequences */
int GoodRand();
/* returns random numbers on the interval [0, 1) -- maybe a mersenne twister */
double GoodDblRand();
int Rand1()
{
return 100 + (int) (GoodDblRand()*51.0/RAND_MAX);
}
int Rand2()
{
return 100 + (int) (GoodDblRand()*51);
}
Peruse this thread.
http://www.codeguru.com/forum/showthread.php?t=317008