编写一段代码,完成 n × n 矩阵的转置操作,矩阵各元素值随机生成,使用c语言。
时间: 2024-03-23 10:43:25 浏览: 19
以下是一种简单的实现方式:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n = 3; // 矩阵维度
int mat[n][n];
int i, j;
// 随机生成矩阵元素
srand(time(NULL));
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
mat[i][j] = rand() % 10;
printf("%d ", mat[i][j]); // 输出原始矩阵
}
printf("\n");
}
// 转置矩阵
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
int tmp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = tmp;
}
}
printf("转置后的矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d ", mat[i][j]); // 输出转置后的矩阵
}
printf("\n");
}
return 0;
}
```
代码中使用了 `srand()` 函数和 `rand()` 函数生成随机数,`time()` 函数用于获取当前时间作为随机数种子。然后使用嵌套循环生成矩阵,并输出原始矩阵。接着使用另外两个嵌套循环遍历矩阵,进行转置操作。最后输出转置后的矩阵。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)