C语言实现矩阵翻转(上下翻转、左右翻转)
C语言实现矩阵翻转 上下翻转与左右翻转
实例代码:
#include <stdio.h> void matrix (int m, int n, int t) { int arr[m][n]; int i, j, k; for (i = 0; i < m; i++){ for (j = 0; j < n; j++){ scanf("%d", &arr[i][j]); } } if (t == 0){//左右翻转 for (i = 0; i < m; i++){ for (j = n-1; j >= 0; j--){ if ( j == 0 ) { printf("%d", arr[i][j]); } else { printf("%d ", arr[i][j]); } } printf("\n"); } } else if (t == 1){//上下翻转 for (i = m-1; i >= 0; i--){ for (j = 0; j < n; j++){ if ( j == n - 1 ) { printf("%d", arr[i][j]); } else { printf("%d ", arr[i][j]); } } printf("\n"); } } } int main() { int m, n, t; scanf("%d %d %d", &m, &n, &t); matrix (m, n, t); return 0; }
动态分配内存
void matrix (int m, int n, int t) { int i, j; int **arr=(int**)malloc(m*sizeof(int*)); for(i = 0; i < m; i++) { arr[i] = (int*)malloc(n * sizeof(int)); for(j = 0; j < n;j++) { scanf("%d", &arr[i][j]); } } /* int **arr = new int*[m]; for(i=0;i<m;i++) { arr[i] = new int[n]; for(j=0;j<n;j++) { scanf("%d", &arr[i][j]); } } */ if (t == 0){//左右翻转 for (i = 0; i < m; i++){ for (j = n-1; j >= 0; j--){ if ( j == 0 ) { printf("%d", arr[i][j]); } else { printf("%d ", arr[i][j]); } } printf("\n"); } } else if (t == 1){//上下翻转 for (i = m-1; i >= 0; i--){ for (j = 0; j < n; j++){ if ( j == n - 1 ) { printf("%d", arr[i][j]); } else { printf("%d ", arr[i][j]); } } printf("\n"); } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
赞 (0)