代码生成(用C语言写一个用一门高级编程语言生成0~999 999(均包含,或者更大范围)之间的随机整数20 000个,要求随机数都不相同(如相同,则需要去重复并重新生成当前随机数),即,得到20 000个两两不同的随机数。)
时间: 2023-11-24 20:05:11 浏览: 66
以下是一个用C语言实现的生成随机数的代码,使用了线性同余法生成随机数,并使用了哈希表去重:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_LENGTH 20000
#define MOD 1000000
bool hash[MOD] = {false};
int main() {
int random_nums[MAX_LENGTH];
int cnt = 0;
int a = 1664525, c = 1013904223;
int x = rand() % MOD;
while (cnt < MAX_LENGTH) {
x = (a * x + c) % MOD;
if (!hash[x]) {
hash[x] = true;
random_nums[cnt++] = x;
}
}
for (int i = 0; i < MAX_LENGTH; i++) {
printf("%d ", random_nums[i]);
}
printf("\n");
return 0;
}
```
其中,a和c分别为线性同余法的参数,x为当前随机数,使用哈希表来判断随机数是否重复。
相关问题
代码生成( 用C语言生成0~999 999(均包含,或者更大范围)之间的随机整数20 000个,要求随机数都不相同(如相同,则需要去重复并重新生成当前随机数),即,得到20 000个两两不同的随机数。)
可以使用C语言中的rand()函数生成随机数,同时使用数组来存储已经生成的随机数,通过循环判断新生成的随机数是否与数组中已有的数重复,如果重复了就重新生成,直到得到20 000个不同的随机数为止。具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 1000000 // 生成随机数的最大值(不包含)
int main()
{
int nums[20000]; // 存储随机数的数组
int count = 0; // 已经生成的随机数个数
srand((unsigned int)time(NULL)); // 初始化随机数种子
while (count < 20000) {
int num = rand() % MAX_NUM;
int i;
// 判断是否与已有的数重复
for (i = 0; i < count; i++) {
if (nums[i] == num) {
break;
}
}
// 如果不重复,则将新数存入数组
if (i == count) {
nums[count++] = num;
}
}
// 输出生成的随机数
for (int i = 0; i < 20000; i++) {
printf("%d ", nums[i]);
}
return 0;
}
```
用C语言生成0~999 999(均包含,或者更大范围)之间的随机整数20 000个,要求随机数都不相同(如相同,则需要去重复并重新生成当前随机数),即,得到20 000个两两不同的随机数。
可以使用C语言中的rand()函数生成随机数,但是需要注意的是,rand()函数生成的随机数是伪随机数,即它们是通过一定的算法计算出来的,并不是真正的随机数。如果要避免重复的随机数,可以将生成的随机数存入一个数组中,每次生成新的随机数时,都要检查数组中是否已经存在相同的随机数。
以下是实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 1000000 // 生成随机数的最大值
#define ARRAY_SIZE 20000 // 数组大小
int main() {
int arr[ARRAY_SIZE] = {0}; // 存储随机数的数组
int i, j, num;
srand((unsigned) time(NULL)); // 设置随机数种子
for (i = 0; i < ARRAY_SIZE; i++) {
num = rand() % MAX_NUM; // 生成随机数
for (j = 0; j < i; j++) { // 检查数组中是否已经存在相同的随机数
if (arr[j] == num) {
i--; // 如果存在相同的随机数,重新生成当前随机数
break;
}
}
arr[i] = num; // 将不重复的随机数存入数组
}
for (i = 0; i < ARRAY_SIZE; i++) {
printf("%d ", arr[i]); // 输出随机数
}
printf("\n");
return 0;
}
```
该程序使用srand()函数设置随机数种子,以确保每次运行程序都能生成不同的随机数序列。在生成随机数时,使用取模运算将生成的随机数限制在0~999 999之间。循环检查数组中是否已经存在相同的随机数,如果存在相同的随机数,则重新生成当前随机数。最终将生成的随机数存入数组,并输出到屏幕上。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)