我知道可以使用
生成整数随机数 (rand() % (difference_between_upper_and_lower_limit)) + lower_limit
我想知道是否有一种方法可以生成介于0.1和0.01之间的数字。
我试过了
double speed = (rand() % 10)/100;
但这总是给我0.0000000;
预先谢谢!!
答案 0 :(得分:2)
我认为,您错过了类型转换部分==> ((double)(rand()%10))/ 100;
尝试此代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
// If you don't set the seed-value, you'll always get the same random numbers returned in every execution of the code
srand(time(0));
double speed = ((double)(rand() % 10))/100;
printf("%f\n", speed );
speed = ((double)(rand() % 10))/100;
printf("%f\n", speed );
speed = ((double)(rand() % 10))/100;
printf("%f\n", speed );
speed = ((double)(rand() % 10))/100;
printf("%f\n", speed );
return 0;
}
答案 1 :(得分:2)
您可以使用以下任意间隔创建均匀分布
((double)rand()/RAND_MAX)*(i_end-i_start)+i_start
其中i_start
和i_end
表示间隔的开始和结束。
在您的情况下,请尝试
((double)rand()/RAND_MAX)*0.09+0.01
答案 2 :(得分:1)
double upper_limit = .1;
double lower_limit = .01;
double value = ((upper_limit-lower_limit)*rand())/RAND_MAX + lower_limit;