如果 x 和 y 值不同,如何在 x-y 范围内生成随机数 [语言 C]
How to generate random number within x-y range, if x and y values varies [language C]
如何在C中生成x-y范围内的随机数
其中
X : [t , t+m] and Y : [r , r+m ].
也就是说,如果x从t变化到t+n,y从r变化到r+n。
基本上,您使用操作系统滴答计数作为生成器的种子,用上限范围对生成的数字取模,然后将下限范围添加到结果中。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
double x = 1.0;
double y = 2.0;
srand(time(NULL));
// Guarenateed keep x1 between x and y.
double x1 = x + rand()*(y-x)/RAND_MAX;
printf("x1: %lf\n", x1);
return 0;
}
如何在C中生成x-y范围内的随机数 其中
X : [t , t+m] and Y : [r , r+m ].
也就是说,如果x从t变化到t+n,y从r变化到r+n。
基本上,您使用操作系统滴答计数作为生成器的种子,用上限范围对生成的数字取模,然后将下限范围添加到结果中。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
double x = 1.0;
double y = 2.0;
srand(time(NULL));
// Guarenateed keep x1 between x and y.
double x1 = x + rand()*(y-x)/RAND_MAX;
printf("x1: %lf\n", x1);
return 0;
}