【发布时间】:2016-02-29 10:48:02
【问题描述】:
我试图让两个具有随机生成的数字的矩阵相乘,但我不断遇到分段错误,并且不知道如何正确分配内存。
这方面的任何帮助都会很棒
//这里是代码
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<ctime>
using namespace std;
int main()
{
srand (1023);
int a[1000][1000], b[1000][1000], mult[1000][1000], r1, c1, r2, c2, i, j, k;
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
while (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.";
}
cout << endl << endl;
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 1
}
cout << endl<< endl;
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 2
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
mult[i][j]=rand()%9+1;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
mult[i][j]+=a[i][k]*b[k][j]; //matrix multiplication
}
cout << endl << "Output Matrix: " << endl;
clock_t begin = clock();
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
cout << " " << mult[i][j];
if(j==c2)
cout << endl;
clock_t end = clock();
double elapsed_secs = double(end-begin)*100;
cout<<"Elapsed Time: "<<elapsed_secs<<" milliseconds\n";
return 0;
}
【问题讨论】:
-
不要使用
int,存储大量数字。 -
您根本没有初始化数组
a和b的元素。访问它们的元素,即使使用有效的索引,也会产生未定义的行为。 -
那么你将如何初始化它们
标签: c++ matrix matrix-multiplication