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.
>>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.
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;
}
Thanks everyone. I meant a floating decimal between -1 and 1, not an int. I've got it now. Thanks again.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.