繁体   English   中英

为什么我使用 C 的矩阵乘法程序不起作用?

[英]Why my program of Matrix multiplication using C doesn't work?

我写了一个程序来计算矩阵乘法。我接受用户输入来定义数组的大小和包含的元素。(我的编程知识应该被认为是初学者)。当我执行程序时,它会打印一个 null 数组。 当我逐行测试代码时。 我发现程序在计算矩阵之前可以正常工作。(接受用户输入并调用函数)。 我找不到问题的根源。 我已经包含了包含乘法 function 的部分代码。

#include <stdio.h>
#define MAX 100
void matrix_mul(int, int, int, int, int [MAX][MAX], int [MAX][MAX]);

int main()
{

int mat_1[MAX][MAX] ,mat_2[MAX][MAX];
int row1, row2, column1, column2;

printf("Input number of rows for the first matrix:  ");
scanf("%d", &row1);
printf("Input number of columns for the first matrix:  ");
scanf("%d", &column1);

printf("Input number of rows for the second matrix:  ");
scanf("%d", &row2);
printf("Input number of columns for the second matrix:  ");
scanf("%d", &column2);

if(column1 != row2 || column2 != row1)
{
    printf("Incompatible matrices. Try Again! ");
    return 0;
}

printf("Enter elements for matrix 1 of order %d x %d\n", row1, column1);

for(int i=0; i<row1; i++)
{
    for(int j=0; j<column1; j++)
        scanf("%d", &mat_1[i][j]);
}

printf("\n\nEnter elements for matrix 1 of order %d x %d\n", row2, column2);

for(int i=0; i<row2; i++)
{
    for(int j=0; j<column2; j++)
        scanf("%d", &mat_2[i][j]);
}
 matrix_mul(row1, row2, column1, column2, mat_1, mat_2);

}

// for testing r1 = 3 c1 =2 r2 =2 c2 =3
void matrix_mul(int row1, int row2, int column1, int column2, int ar1[MAX][MAX], int ar2[MAX][MAX])
{

    int arr [MAX][MAX]; 

    for(int i=0 ; i<row1; i++)
    {

        for(int j=0; j<column2; j++)
        {
            int sum = 0;
            for(int k=0; k<column1; k++)
                sum += ar1[row1][k] * ar2[column1][row1];
            printf("%d", sum);
            arr[row1][column2] = sum;
        }
    }

    for(int i=0; i<row1; i++)
    {
        for(int j=0; j<column2; j++)
            printf("%d ", arr[i][j]);
        printf("\n");
    }

}

您将循环值与边界混合在一起。 以下是相关行的更正版本:

            sum += ar1[i][k] * ar2[k][j];
        arr[i][j] = sum;

您看到的是88888而不是8 ,因为您在以下位置留下了调试语句:

printf("%d", sum);

删除它,您只会看到正确的 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM