c - 3x3 数组 = 10 个数字

标签 c arrays

我有这个代码

#include <math.h>
#include <stdio.h>

const int n = 3;
const int s = 3;
int getm(int mat[n][s]);
int printm(int mat[n][s]);

int main()
{
    int m[n][s];
    getm(m);
    printm(m);
    return 0;
}

int getm(int mat[n][s])
{
    for(int x = 0;x < n;x++)
    {
        for (int y = 0;y<s;y++)
        {
            scanf("%i ", &mat[x][y]);
        }
    }
    return 0;
}
int printm(int mat[n][s])
{
    for(int x = 0;x<n;x++)
    {
        for(int y = 0;y<s;y++)
        {
            printf("%i ", mat[x][y]);
            if(y==(s-1))
            {
                printf("\n");
            }
        }
    }
}

应该要求 9 个数字来制作 3x3 矩阵数组,但它实际上要求 10 个数字,printm 运行良好 - 仅打印 9 个数字。错误在哪里?

最佳答案

我认为问题在于 %i 之后的空格:您不需要第十个数字,但您的代码无论如何都在请求它,因为它等待在第九个数字之后获得一个空格。

另外,您可以通过删除 if 来稍微优化您的打印​​代码:

for(int x = 0;x<n;x++)
{
    for(int y = 0;y<s;y++)
    {
        printf("%i ", mat[x][y]);
    }
    printf("\n");
}

关于c - 3x3 数组 = 10 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12654029/

相关文章:

python - Numpy hstack - "ValueError: all the input arrays must have same number of dimensions"- 但他们这样做

c - 查找列表中重复的对数

Java 2D 数组填充 - 无辜的优化导致严重的减速

c - 如何在 C 中修改共享内存(shmget/shmat)?

c - 如何计算c中的整数幂

c - 为什么网络程序将IP地址存储在IP地址结构中

c - 有没有一种简单的方法可以从 C 中的字符串数组创建字符串?

c - 声明和定义相互引用的初始化常量结构的最佳方法

php - 在编写查询时需要帮助

.net - List<T>.Contains() 很慢?