matrix - 为什么我的矩阵在乘以 A *B 后显示随机数?
问题描述
所以我有这个任务,我必须编写一个对两个矩阵进行乘法运算的程序。我的程序询问用户两个矩阵的行数和列数。为了生成矩阵的值,我使用了 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
抱歉,如果格式不是最好的,这是我的第一篇文章,我是编程新手。提前致谢。
解决方案
推荐阅读
- node.js - 在 mysql 查询中获取模式信息
- android - 如何访问可移动存储设备,例如 micro SD 卡和 USB 驱动器?
- reactjs - 在新标签中全屏显示图像
- android - androidx 导航:@NonNull 公共开放乐趣的参数太多
- c++ - 使用 va_list 生成字符串
- c# - 使用身份登录时如何验证用户的角色
- java - 将字符串从 JLabel 数组存储到字符串数组
- ios - 组合:监听内部集合变化
- python - 使用 dask ml StandardScaler 的属性错误
- java - 给定用户选择目录的 URI,如何根据参数化文件名读取文件?