【问题标题】:Creating a matrix that has its elements as the sum of the indices of that element创建一个矩阵,其元素作为该元素的索引之和
【发布时间】:2021-11-18 17:06:51
【问题描述】:
int main() {
    int n = 0;
    int matrix[n][n];

    printf("Insert the order of the matrix:");
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            matrix[i][j] = i + j;

    printf("The matrix is:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
    } 

对于 2x2 矩阵,输出应该是 0 1 1 2,但它是 1 2 1 2,对于 3x3 矩阵,它应该是 0 1 2 1 2 3 2 3 4,但它显示 2 3 4 2 3 4 2 3 4

问题是我的输出总是矩阵的第一行,重复 n 次。有什么帮助吗?

【问题讨论】:

  • 你应该在scanf("%d", &amp;n);之后声明int matrix[n][n];,因为当你声明数组时n是0。
  • 当您声明int matrix[n][n] 时,n 的值为0

标签: c matrix multidimensional-array


【解决方案1】:
#include <stdio.h>

int main() {
    int n = 0;
    printf("Insert the order of the matrix:");
    scanf("%d", &n);
    int matrix[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            matrix[i][j] = i + j;

    printf("The matrix is:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
    }
}

【讨论】:

  • 请不要只转储代码。总是解释原始代码有什么问题。
【解决方案2】:

您声明大小为n 的数组为零。然后行的长度为零,因此每个连续行的偏移量也为零。这意味着所有行都存储在同一个位置。作为最终结果,最后一行的值会覆盖之前的所有行。

输入n之前声明matrix[n][n]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多