Hi.

If I want to generate random numbers between -1 and 1, do I need to write a function to do that or is their something in the stdlib that can do it?

Thanks.

Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster

>>If I want to generate random numbers between -1 and 1

Why? The only number between -1 and 1 is 0. -1, 0 and 1 are all integers, there are no fractions in integer math. rand() returns an integer. So if you want a float return value, such as 0.123 then you will have to write a function that puts the return value from rand() into a float variable then divide it by RAND_MAX (defined in stdlib.h) to make it less than 1. I'm not sure how to make a random number between -1.0 and 0 other than just simply arbitrarily make the result from the above calculations negative.

Dave Sinkula
2,398
long time no c
Team Colleague

If I want to generate random numbers between -1 and 1, do I need to write a function to do that or is their something in the stdlib that can do it?

Something like this, perhaps?

```
double drand(void)
{
return 2.0 * rand() / (RAND_MAX + 1.0) - 1.0;
}
```

puppy
0
Newbie Poster

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.