生成随机的二维数组c语言
时间: 2024-08-21 17:00:52 浏览: 81
在C语言中,生成随机的二维数组通常涉及到标准库函数`rand()`和`srand()`,以及一些基本数据结构的组合。以下是一个简单的示例,展示如何创建一个指定大小的随机整数二维数组:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义数组的行和列
#define ROWS 5
#define COLS 7
void generate_random_array(int arr[][COLS]) {
// 设置随机数种子,保证每次运行程序得到的结果一致(为了演示)
srand(time(0));
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
// 使用rand()生成介于0到RAND_MAX之间的随机数,并转换为指定范围内的整数
arr[i][j] = rand() % 10 + 1; // 这里假设范围是1到10
}
}
// 打印生成的数组
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int array[ROWS][COLS]; // 二维数组声明
generate_random_array(array);
return 0;
}
```
这个例子中,`generate_random_array`函数会生成一个5x7的二维数组,每个元素都是1到10之间的随机整数。你可以根据需要调整`ROWS`、`COLS`和随机值的范围。
阅读全文
相关推荐


















