如何将 rand() 结果设置为一定范围内的值,包括负数? [英] How to set rand() result to values in a certain range including negatives?
本文介绍了如何将 rand() 结果设置为一定范围内的值,包括负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试动态分配一个双精度数组并将每个元素设置为一个正数或负数范围内的随机值,但我遇到了困难.
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.
现在,我只能弄清楚如何设置数字 0 - 最大值.
Right now, I can only figure out how to set numbers 0 - max.
这是我目前所拥有的:
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;
}
我最好的猜测:
for (int i = 0; i < size; i++)
array0[i]=((max + min) * rand() / RAND_MAX) - min;
推荐答案
Range 应该是 (max - min),您可以预先计算乘法因子除以 RAND_MAX.
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;
这篇关于如何将 rand() 结果设置为一定范围内的值,包括负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文