【问题标题】:im getting the wrong answer while i multiply 2 matrices using array of pointers using c当我使用 c 使用指针数组乘以 2 个矩阵时,我得到了错误的答案
【发布时间】:2020-09-22 13:17:45
【问题描述】:

我需要使用 指针数组 来将 2 个矩阵相乘。它的工作,但我得到错误的输出 .如果我给出 m1=n1=m2=n2 = 2 并且两个矩阵都为1 2 3 4。我得到的 o/p 矩阵为7 17 32 54,而正确答案是7 10 15 22。请帮助我,我在这里停留了 2 天...................................................... ....................................

#include <stdio.h>
#include <stdlib.h>

int main()

{

    int m1,n1,m2,n2,i,j,k,sum=0,*a[10],*b[10],*c[10];   
    printf("Enter m1 and n1 : ");
    scanf("%d%d",&m1,&n1);
    printf("Enter m2 and n2 : ");
    scanf("%d%d",&m2,&n2);
    if(n1==m2)
    {
        for(i=0;i<m1;i++)
        {
            a[i] = (int *)malloc(n1*sizeof(int));
        }
        for(i=0;i<m2;i++)
        {
            b[i] = (int *)malloc(n2*sizeof(int));
        }
        for(i=0;i<m1;i++)
        {
            c[i] = (int *)malloc(n2*sizeof(int));
        }
        printf("Enter the first matrix : ");
        for(i=0;i<m1;i++)
        {
            for(j=0;j<n1;j++)
            {
                scanf("%d",(*(a+i)+j));
            }
        }
        printf("Enter the second matrix : ");
        for(i=0;i<m2;i++)
        {
            for(j=0;j<n2;j++)
            {
                scanf("%d",(*(b+i)+j));
            }
        }

        for(i=0;i<m1;i++)
        {
            for(j=0;j<n2;j++)
            {
                for(k=0;k<n2;k++)
                {
                    sum += a[i][k] * b[k][j];
                }
                *(*(c+i)+j) = sum;
            }
        }
        printf("The Resultant Matrix : ");
        for(i=0;i<m1;i++)
        {
            for(j=0;j<n2;j++)
            {
                printf("%d ",*(*(c+i)+j));
            }
        printf("\n");
        }
    }
    else
    printf("Invalid Matrix\n");
}

【问题讨论】:

  • 因为这是C,所以这个表达式(以及其他类似的):a[i] = (int *)malloc(n1*sizeof(int)); 应该表示为a[i] = malloc(n1*sizeof(int));,因为it is not recommeded to cast the return of malloc() and family in C
  • 但是我不能以任何其他方式使用指针数组并且类型转换工作正常,因为当我打印 2 个数组 a 和 b 时我得到 1 2 3 4
  • 但是我不能使用指针数组。真的吗?

标签: c


【解决方案1】:

您忘记在计算每个元素之前初始化sum

                sum = 0; /* add this */

                for(k=0;k<n2;k++)

                {

                    sum += a[i][k] * b[k][j];

                }

                *(*(c+i)+j) = sum;

【讨论】:

  • @KrevoL 实际输出是预期输出的累积总和。这表明错误是由于缺乏初始化造成的。
  • @KrevoL,在程序开始时将sum 初始化为零是不够的。您需要在结果矩阵的每个元素的计算开始时将其 [返回] 设置为零。
  • @JohnBollinger 谢谢 manh 。我没有注意到。终于成功了!!
  • @MikeCAT 谢谢老兄.....它工作。感谢您的帮助 manh
猜你喜欢
  • 1970-01-01
  • 2012-10-11
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多