所以我有这个任务,我必须编写一个程序来对两个矩阵进行乘法。 我的程序询问用户两个矩阵的行数和列数。 为了生成矩阵的值,我使用了 rand 函数,然后显示了生成的矩阵。
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
int FA, CA,num; //number is to store the random number
cout<<"Enter the number of rows for MATRIX A "<<endl;
cin>>CA;
cout<<"Enter the number of columns for MATRIX A "<<endl;
cin>>FA;
int A[FA][CA];
int i, j;
for(i=0;i<FA;i++)
{
for(j=0;j<CA;j++)
{
num=rand()%10; //it generates a number ranging from 0 to 10
A[FA][CA] = num;
cout<<" "<<A[FA][CA];
}
cout<<endl;
}
int FB, CB;
cout<<"Enter the number of rows for MATRIX B "<<endl;
cin>>CB;
cout<<"Enter the number of rows for MATRIX B "<<endl;
cin>>FB;
int B[FB][CB];
for(i=0;i<FB;i++)
{
for(j=0;j<CB;j++)
{
num=rand()%10;
A[FB][CB] = num;
cout<<" "<<A[FB][CB];
}
cout<<endl;
}
到目前为止一切顺利,接下来在 if 语句中,它检查乘法是否可以完成。 然后是使实际操作可以这么说的代码部分...... 我感觉这里有问题,但我找不到。 这是:
if(FB == CA)
{
cout<<"Multiplication in progress"<<endl;
cout<<endl;
//Creating MATRIX AB
int AB[FA][CB];
int k;
cout<<"MATRIX AB, HAS: "<< FA << " ROWS AND "<< CB << " COLUMNS."<<endl;
//MULTIPLICATION PROCESS
// START
for(i=0;i<FA;i++)
{
for(j=0;j<CB;j++)
{
AB[i][j]=0;
for(k=0;k<CA;k++)
{
AB[i][j]+=A[i][k]*B[k][j];
}
}
cout<<endl;
} //finish
// SHOW AB
for (int i = 0; i < FA; i++)
{
for (int j = 0; j < CB; j++)
{
cout << AB[i][j] << " ";
}
// Newline for new row
cout << endl;
}
}
else
{
cout<<"Multiplication can't be done"<<endl;
}
return 0;
}
问题在于 AB 矩阵显示随机数。 我似乎无法找到问题所在。 这是它显示的内容:
[在此处输入图片说明][1]
[1]:https://i.stack.imgur.com/FhBN5.png
对不起,如果格式不是最好的,这是我的第一篇文章,我是编程新手。提前致谢。