例如,假设存在宽度和高度,则6和4分别来自用户输入,并且存储在2D数组中的输入(也来自用户输入)是:
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0
有没有办法翻转x轴和y轴?
我想做的就是改变
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0
进入
0 1 1 0
1 0 0 1
2 0 0 1
2 0 0 1
1 0 0 1
0 1 1 0
下面的代码,
scanf("%d %d", &width, &height);
int board[height][width];
for(i = 0; i < height; i++)
{
for(j = 0; j < width; j++)
{
scanf("%d", &input);
board[i][j] = input;
}
}
并通过
for(i = 0; i < width; i++)
{
for(j = 0; j < height; j++)
{
printf("%d", board[j][i]);
}
printf("\n");
}
,这会打印出我期望的输出,但是实际上并没有改变其位置...我无法更改第一个编码部分,因为我已经使用它来完成其他工作。是否有通过添加其他方法或新板来解决问题的方法?
有人可以帮帮我吗?如果有人帮助我,我将非常感激!
谢谢
最佳答案
只需声明第二个数组,指定的行数等于width
并且列数等于height
,然后将值从源数组复制到第二个数组。
例如
#include <stdio.h>
int main(void)
{
size_t height, width;
printf( "Enter the height and the width of the array: " );
scanf( "%zu %zu", &height, &width );
int a[height][width];
puts( "Enter values for elements of the array" );
for ( size_t i = 0; i < height; i++ )
{
printf( "%zu row: ", i + 1 );
for ( size_t j = 0; j < width; j++ ) scanf( "%d", &a[i][j] );
}
int b[width][height];
for ( size_t i = 0; i < height; i++ )
{
for ( size_t j = 0; j < width; j++ ) b[j][i] = a[i][j];
}
puts( "\nSource array is" );
for ( size_t i = 0; i < height; i++ )
{
for ( size_t j = 0; j < width; j++ ) printf( "%d ", a[i][j] );
putchar( '\n' );
}
puts( "\nReversed array is" );
for ( size_t i = 0; i < width; i++ )
{
for ( size_t j = 0; j < height; j++ ) printf( "%d ", b[i][j] );
putchar( '\n' );
}
return 0;
}
程序输出可能看起来像
Enter the height and the width of the array: 4 6
Enter values for elements of the array
1 row: 0 1 2 2 1 0
2 row: 1 0 0 0 0 1
3 row: 1 0 0 0 0 1
4 row: 0 1 1 1 1 0
Source array is
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0
Reversed array is
0 1 1 0
1 0 0 1
2 0 0 1
2 0 0 1
1 0 0 1
0 1 1 0
另一种方法是动态分配第一和辅助数组。
例如
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t height, width;
printf( "Enter the height and the width of the array: " );
scanf( "%zu %zu", &height, &width );
int **a = malloc( height * sizeof( int * ) );
for ( size_t i = 0; i < height; i++ ) a[i] = malloc( width * sizeof( int ) );
puts( "Enter values for elements of the array" );
for ( size_t i = 0; i < height; i++ )
{
printf( "%zu row: ", i + 1 );
for ( size_t j = 0; j < width; j++ ) scanf( "%d", &a[i][j] );
}
int **b = malloc( width * sizeof( int * ) );
for ( size_t i = 0; i < width; i++ ) b[i] = malloc( height * sizeof( int ) );
for ( size_t i = 0; i < height; i++ )
{
for ( size_t j = 0; j < width; j++ ) b[j][i] = a[i][j];
}
puts( "\nSource array is" );
for ( size_t i = 0; i < height; i++ )
{
for ( size_t j = 0; j < width; j++ ) printf( "%d ", a[i][j] );
putchar( '\n' );
}
for ( size_t i = 0; i < height; i++ ) free( a[i] );
free( a );
a = b;
puts( "\nReversed array is" );
for ( size_t i = 0; i < width; i++ )
{
for ( size_t j = 0; j < height; j++ ) printf( "%d ", a[i][j] );
putchar( '\n' );
}
for ( size_t i = 0; i < width; i++ ) free( a[i] );
free( a );
return 0;
}