gpt4 book ai didi

c - 矩阵乘法

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:39 25 4
gpt4 key购买 nike

我不明白哪里错了。请帮我改正。输出结果矩阵的所有元素都为零。

 #include<stdio.h>
#include<conio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i=0,j=0,row1,col1,row2,col2,row3,col3,s=0,k=0,l=0;
printf("Enter no. of rows and no. of columns of first matrix:\n");
scanf("%d %d",&row1,&col1);
printf("Enter no. of rows and no. of columns of second matrix:\n");
scanf("%d %d",&row2,&col2);
if(col1==row2)
{
row3=row1;
col3=col2;
}
else
{
printf("Not possible!");
exit(1);
}

printf("Enter elements of first matrix:\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&a[i][j]);
}
}


printf("Enter elements of second matrix:\n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}

i=0;
j=0;

for(k=0;k<row3;k++)
{
for(l=0;l<col3;l++)
{

while(i<row3 || j<col3)
{
//printf("Hi");
s=s+a[i][j++]*b[i++][j];
//printf("%d\n",s);

}

}
printf("%d\n",s);
c[k][l]=s;
s=0;
}


printf("Sum matrix is:\n");
for(k=0;k<row3;k++)
{
for(l=0;l<col3;l++)
{
printf("%d ",c[k][l]);
}
printf("\n");
}
getch();
}

我在 while 循环中包含了打印注释以便进行调试,但它没有帮助。

最佳答案

您在列循环之外设置结果,因此每行只设置一个结果。通过在大括号内移动这 3 行来更改代码:

for(k=0;k<row3;k++)
{
for(l=0;l<col3;l++)
{
i = 0; j = 0;
while(i<row3 || j<col3)
{
//printf("Hi");
s=s+a[k][j++]*b[i++][l];
//printf("%d\n",s);
}

// THIS CODE HAS MOVED:
printf("%d\n",s);
c[k][l]=s;
s=0;
}
}

此外,您的添加需要使用 k 和 l 索引,以便您沿着 k 给定的 a[][] 行和 l 给定的 b[][] 列移动:

s=s+a[k][j++]*b[i++][l];

关于c - 矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28082668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com