【发布时间】:2021-02-26 05:25:35
【问题描述】:
我正在创建一个程序的一部分,它应该允许用户输入方阵的尺寸,为每个元素输入一个值,然后打印出结果矩阵。很确定问题出在其中一个 for 循环中,因为只打印了矩阵的最后一行;例如,如果我想要一个 [1 2 3][4 5 6][7 8 9] 的 3x3 矩阵,程序将打印 [7 8 9][7 8 9][7 8 9]。
//initialise variables
int n_i = 0;
int input_matrix[n_i][n_i];
int row;
int column;
//dimensions of matrix
printf("Enter a value for the dimensions of a square matrix: \n");
printf(">>");
scanf("%i", &n_i);
//elements of matrix
for(row = 0; row < n_i; ++row)
{
for(column = 0; column < n_i; ++column)
{
printf("Enter a value for the [%i][%i] element: \n", row, column);
printf(">>");
scanf("%d", &input_matrix[row][column]);
}
}
//display matrix
printf("%ix%i matrix: \n", n_i, n_i);
for(row = 0; row < n_i; ++row)
{
for(column = 0; column < n_i; ++column)
{
printf("%d ", input_matrix[row][column]);
printf("%i ", n_i);
if(column == n_i)
{
printf("\n");
}
}
}
【问题讨论】:
-
在询问为什么某些代码不起作用时,请始终提供minimal reproducible example。
标签: c for-loop matrix multidimensional-array