用c写一个矩阵旋转输出
时间: 2024-06-12 15:05:20 浏览: 10
以下是一个用C语言编写的矩阵旋转输出程序:
```c
#include <stdio.h>
#define MAX_SIZE 100
void rotate(int matrix[MAX_SIZE][MAX_SIZE], int n) {
int temp;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[j][n - i - 1];
matrix[j][n - i - 1] = matrix[n - i - 1][n - j - 1];
matrix[n - i - 1][n - j - 1] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = temp;
}
}
}
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int n;
int matrix[MAX_SIZE][MAX_SIZE];
printf("请输入矩阵的维度:");
scanf("%d", &n);
printf("请输入矩阵的元素:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
rotate(matrix, n);
printf("旋转后的矩阵为:\n");
printMatrix(matrix, n);
return 0;
}
```
这个程序首先读取矩阵的维度和元素,然后调用 `rotate` 函数旋转矩阵,最后输出旋转后的矩阵。其中 `rotate` 函数使用了一个经典的算法,即将矩阵分成四个相等的部分,然后对于每个部分中的元素,依次将其与对应位置上的元素交换。这样就可以完成矩阵的旋转。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)