You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求排查C语言矩阵乘法代码错误:输出文件无内容

矩阵乘法程序错误分析与修复

代码中的关键错误及解决方法:

  • 循环逻辑错误(核心问题)

    1. 矩阵乘法的内层j循环条件写错:原代码是for (int j = 0; i < c2; j++),把j < c2误写为i < c2,导致循环无法正常执行,m3数组根本没被正确计算。
    2. k循环范围错误:矩阵乘法中,k需要遍历第一个矩阵的列数(即第二个矩阵的行数),原代码用了k < r1,正确应为k < c1(前提是c1 == r2,否则矩阵无法相乘)。
  • 文件操作位置错误
    原代码把文件打开、写入、关闭的逻辑放在了外层i循环内部,还执行了return 0,导致程序第一次循环就直接退出,矩阵乘法未完成就写入,自然得不到有效结果。需将文件操作放在所有乘法计算完成之后。

  • fopen参数错误
    fopen("output.txt", 'w')中第二个参数用了单引号的字符'w',而fopen要求传入字符串常量"w",这个错误会导致文件打开失败。

  • 缺少合法性检查
    未验证第一个矩阵的列数c1是否等于第二个矩阵的行数r2,这是矩阵乘法的必要前提,不满足时应提示用户并终止程序。

  • 输出格式优化(非功能性但提升可读性)
    原代码写入文件时数字无分隔符,会挤在一起,建议添加空格分隔元素。

修正后的完整代码:

#include <stdio.h>

int main()
{
    int r1, r2, c1, c2;
    printf("Enter number of rows and columns for mat1-");
    scanf("%d %d", &r1, &c1);
    int m1[r1][c1];
    for (int i = 0; i < r1; i++)
    {
        for (int j = 0; j < c1; j++)
        {
            printf("Enter mat1[%d][%d]-", i + 1, j + 1);
            scanf("%d", &m1[i][j]);
        }
    }

    printf("Enter number of rows and columns for mat2-");
    scanf("%d %d", &r2, &c2);
    // 检查矩阵乘法合法性
    if (c1 != r2)
    {
        printf("Error: Matrix multiplication not possible! Columns of mat1 must equal rows of mat2.\n");
        return 1;
    }
    int m2[r2][c2];
    for (int i = 0; i < r2; i++)
    {
        for (int j = 0; j < c2; j++)
        {
            printf("Enter mat2[%d][%d]-", i + 1, j + 1);
            scanf("%d", &m2[i][j]);
        }
    }

    int m3[r1][c2];
    // 正确的矩阵乘法循环
    for (int i = 0; i < r1; i++)
    {
        for (int j = 0; j < c2; j++)
        {
            int sum = 0;
            for (int k = 0; k < c1; k++)
            {
                sum += m1[i][k] * m2[k][j];
            }
            m3[i][j] = sum;
        }
    }

    // 矩阵计算完成后再处理文件
    FILE *outputFile = fopen("output.txt", "w");
    if (outputFile == NULL)
    {
        printf("Error opening file!\n");
        return 1;
    }
    // 写入文件,添加空格分隔元素
    for (int i = 0; i < r1; i++)
    {
        for (int j = 0; j < c2; j++)
        {
            fprintf(outputFile, "%d ", m3[i][j]);
        }
        fprintf(outputFile, "\n");
    }
    fclose(outputFile);
    printf("Result written to output.txt successfully.\n");
    return 0;
}

内容的提问来源于stack exchange,提问作者Ritam26

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:58:12