如何生成0.1到0.01之间的随机数

问题描述 投票:-2回答:3

我知道有可能使用生成整数随机数

(rand() % (difference_between_upper_and_lower_limit)) + lower_limit

我想知道是否有一种方法可以生成0.1到0.01之间的数字。我试过double speed = (rand() % 10)/100;但它总是给我0.0000000;在此先感谢!`

c random
3个回答
2
投票

您可以使用任意间隔创建均匀分布

((double)rand()/RAND_MAX)*(i_end-i_start)+i_start

其中i_starti_end表示间隔的开始和结束。

在你的情况下尝试

((double)rand()/RAND_MAX)*0.09+0.01

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
投票
double upper_limit = .1;
double lower_limit = .01;
double value = ((upper_limit-lower_limit)*rand())/RAND_MAX + lower_limit;
© www.soinside.com 2019 - 2024. All rights reserved.