问题
I am trying to dynamically allocate an array of doubles and set each element to a random value within a range of positive or negative numbers, but I am having difficulty.
Right now, I can only figure out how to set numbers 0 - max.
Here is what I have so far:
double *random_arr(int size, double min, double max) {
double *array0 = calloc(size, sizeof(double));
if (array0 == NULL) {
exit(1);
}
for (int i = 0; i < size; i++)
array0[i] = (max * rand() / RAND_MAX);
return array0;
}
My best guess:
for (int i = 0; i < size; i++)
array0[i]=((max + min) * rand() / RAND_MAX) - min;
回答1:
Range should be (max - min), and you can pre-calculate a multiplication factor dividing that by RAND_MAX.
double factor = (max - min) / RAND_MAX;
for (int i = 0; i < size; i++)
array0[i] = (rand() * factor) + min;
回答2:
Assuming rand() returns a floating point number 0<=x<1, you simply need to scale by the range of your desired numbers and then add the minimum.
Example: We want the numbers from -100 to -10
Your range is your max - min which is -10 - (-100) = 90
Let's assume your random number is 0.5
0.5 * 90 + -100 (your minimum) = -55
Let's check edge cases:
random number = 0.0
0.0 * 90 + -100 = -100
random number = 0.9999999999...
0.99999999... * 90 + -100 = -10
Great!
来源:https://stackoverflow.com/questions/16410136/how-to-set-rand-result-to-values-in-a-certain-range-including-negatives