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

矩阵乘法代码可正常运行但无输出,寻求技术协助

问题排查与修复方案

你的代码存在多个关键问题,导致输入后无输出,逐一分析并修复如下:

1. 矩阵输入的下标变量误用

在第二个矩阵的输入循环中,错误使用全局变量i、j作为数组下标,而非循环变量a、b,导致所有输入都写入到m2[0][0]位置(全局变量默认初始为0),其他位置为垃圾值,甚至可能触发数组越界的未定义行为。

2. matMul函数的循环逻辑错误

  • 非法赋值语法:j,k = 0;不是合法的C语法,无法同时给两个变量赋值,需拆分为j = 0; k = 0;。
  • 循环逻辑混乱:原while循环的逻辑完全不符合矩阵乘法的计算规则(矩阵乘法需要三重循环遍历行、列、累加项),导致要么无法进入循环,要么计算逻辑彻底错误。
  • 冗余判断:else if (i>r1)永远不会触发,因为while循环的条件是i < r1,当i >= r1时循环已终止。

3. 其他细节问题

  • void main()不符合C标准,main函数返回类型应为int,并在末尾返回状态值。
  • printf中的换行符使用错误,原代码中的换行是无效格式,需改为\n。

修复后的完整代码

#include <stdio.h>

int main(){
    int r1, r2, c1, c2;

    printf("Enter the number of rows for first matrix: ");
    scanf("%d", &r1);
    printf("Enter the number of columns for first matrix: ");
    scanf("%d", &c1);
    printf("Enter the elements of first matrix:\n");
    int m1[r1][c1];
    for (int a = 0; a < r1; a++){
        for (int b = 0; b < c1; b++){
            scanf("%d", &m1[a][b]);
        }
    }

    printf("Enter the number of rows for second matrix: ");
    scanf("%d", &r2);
    printf("Enter the number of columns for second matrix: ");
    scanf("%d", &c2);
    if (c1 != r2) {
        printf("Matrices can't be multiplied with each other.\n");
        return 1;
    }
    printf("Enter the elements of second matrix:\n");
    int m2[r2][c2];
    for (int a = 0; a < r2; a++){
        for (int b = 0; b < c2; b++){
            scanf("%d", &m2[a][b]);
        }
    }

    int res[r1][c2];
    // 初始化结果矩阵为0
    for (int a = 0; a < r1; a++){
        for (int b = 0; b < c2; b++){
            res[a][b] = 0;
        }
    }

    // 标准矩阵乘法三重循环
    for (int i = 0; i < r1; i++){
        for (int j = 0; j < c2; j++){
            for (int k = 0; k < c1; k++){
                res[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }

    printf("Resultant Matrix:\n");
    for (int i = 0; i < r1; i++){
        for (int j = 0; j < c2; j++){
            printf("%d\t", res[i][j]);
        }
        printf("\n");
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:07:20