Sen-Lung Chen wrote:
Dear All:
I have a question about this below function.The purpose of this
function is to generate one number between a and b.
--------------------------
int gennum(int a, int b)
{
srand(time(NULL));
int range = b-a+1;
int x = (rand())%range;<-- problem occur here
int result = a+x;
return result;
}
----------------
this problem pass compile. However it has floating exception when
execution.
I don't know how to solve this problem. Please help me.
Thanks a lot!
As others have pointed out:
(a) range might be negative.
(b) it might not be a good idea to use % for generating random
integers within a given interval since
(1) depending on RAND_MAX and range the numbers might not
be evenly distributed, and
(2) depending on the implementation of rand(), lower order
bits might not be random.
I would like to add that it is not a good idea to call srand()
within each call to gennum(). Depending on the frequence of calls,
you might get results that would not look random at all. E.g., on
my machine the program
#include <iostream>
#include <cstdlib>
using namespace std;
int gennum(int a, int b)
{
srand(time(NULL));
int range = b-a+1;
int x = (rand())%range;
int result = a+x;
return result;
}
int main ( void ) {
for ( unsigned int i=0; i<10; ++i ) {
std::cout << gennum(0,10) <<'\n';
}
}
produced:
news_group> a.out
6
6
6
6
6
6
6
6
6
6
Even if time(NULL) actually changes from call to call, you are giving
up all the theory that went into the design of rand(). Thus, you cannot
be sure that your results will pass any test for pseudo-randomness.
Best
Kai-Uwe Bux