【问题标题】:For loops not producing the correct output when using user inputFor 循环在使用用户输入时没有产生正确的输出
【发布时间】: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");
        }
    }
}

【问题讨论】:

标签: c for-loop matrix multidimensional-array


【解决方案1】:

这段代码:

int n_i = 0;
int input_matrix[n_i][n_i];

尝试创建一个空矩阵。仅在 n_i 设置为所需值之后定义矩阵。

if 语句中的条件:

if(column == n_i)
    {
        printf("\n");
    }

永远不会是真的,因为它在一个只在column &lt; n_i 时执行的循环中。循环的最后一次迭代发生在column == n_i-1

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多