如何用C语言创建一个99x99的二维数组,并填充随机整数?同时,请提供代码实现以便从这个数组中随机选择一个位置的数作为游戏开始时的猜测目标。
时间: 2025-01-06 18:48:45 浏览: 41
在C语言中,我们可以使用`stdlib.h`库中的`srand()`和`rand()`函数生成随机整数,并利用数组的动态内存分配来创建一个99x99的二维数组。首先,需要包含头文件并初始化随机数种子。然后,我们会遍历数组的每个元素,并填充随机数。最后,我们选择一个随机位置返回该数值作为游戏开始的目标。
以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // 需要引入时间库以获取当前时间作为随机数种子
// 创建99x99的二维数组
int** create_array(int rows, int cols) {
int** arr = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; ++i) {
arr[i] = malloc(cols * sizeof(int));
}
return arr;
}
// 填充数组随机整数
void fill_random(int** arr, int rows, int cols) {
srand(time(0)); // 初始化随机数种子
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
arr[i][j] = rand() % 100; // 生成0到99之间的随机整数
}
}
}
// 从数组中随机选择一个位置
int select_random_position(int** arr, int rows, int cols) {
int random_row = rand() % rows;
int random_col = rand() % cols;
return arr[random_row][random_col];
}
int main() {
int rows = 99;
int cols = 99;
int** my_array = create_array(rows, cols);
if (my_array == NULL) {
printf("Error allocating memory.\n");
return -1;
}
fill_random(my_array, rows, cols);
int target = select_random_position(my_array, rows, cols);
printf("The randomly selected number for the game is: %d\n", target);
// 游戏开始,你可以在此处添加猜数字的游戏逻辑
free(my_array[0]);
for (int i = 0; i < rows; ++i)
free(my_array[i]);
free(my_array);
return 0;
}
```
阅读全文
相关推荐







