# 2、在指定范围内生成随机数

2.1、生成在指定区间start~end之间的随机整数：

```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int Random(int start, int end){
int dis = end - start;
return rand() % dis + start;
}

int main(){
int a[10];
int i = 0;
srand((unsigned)time(NULL));
for (i = 0; i < 10; i++){
a[i] = Random(2, 7);
}

for (i = 0; i < 10; i++){
printf("%d ", a[i]);
}
printf("\n");

return 0;
}```

2.2、生成0~1之间的随机数

```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
double a[10];
int i = 0;
srand((unsigned)time(NULL));
for (i = 0; i < 10; i++){
a[i] = rand() / (RAND_MAX + 1.0);
}

for (i = 0; i < 10; i++){
printf("%f ", a[i]);
}
printf("\n");

return 0;
}```

2.3、生成指定区间start~end上的随机浮点数：

```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

double Random(int start, int end){
int dis = end - start;
printf("dis: %d\n", dis);
return start + dis * (rand() / (RAND_MAX + 1.0));
}

int main(){
double a[10];
int i = 0;
srand((unsigned)time(NULL));
for (i = 0; i < 10; i++){
a[i] = Random(2,4);
}

for (i = 0; i < 10; i++){
printf("%lf ", a[i]);
}
printf("\n");

return 0;
}```

## 3、不使用内置随机数函数的生成方法

```#include <stdio.h>

int main(){
unsigned long long next_random = 1;
for (int i = 0; i < 30; i ++){
next_random = next_random * (unsigned long long)25214903917 + 11;
fprintf(stderr, "%f\n", (((next_random & 0xFFFF) / (float)65536) - 0.5));
}
return 0;
}      ```

297 篇文章59 人订阅

0 条评论