问题描述:

I wrote this function to produce random numbers within a certain range. I noticed that it seems to produce negative numbers more when I included a negative range. e.g. -5 to 5

I am assuming this is not random. Is there a problem with this code?

`int random_number_generator(int lowest, int highest)`

{

srand((unsigned)time(0));

int random_integer;

random_integer = lowest+(rand()%highest);

cout << random_integer << endl;

}

The desired range would be highest-lowest, so you need to write the expression like this:

```
random_integer = lowest+(rand()%(highest-lowest));
```

You can use this code:

```
int srandInit = 0;
float Random(float min, float max)
{
if (srandInit == 0)
{
srand ( (unsigned)time(NULL) );
srandInit = 1;
}
return ((max - min) * ((float)rand() / (float)RAND_MAX)) + min;
}
```

and just make `static_cast`

from `float`

result to `int`

result of next expression is rand number within [ lowest .. highest ] interval

```
random_integer = lowest + ( rand( ) % (highest-lowest + 1) );
```