我輸入矩陣的值。現在它已被修改爲矢量而不是陣列,這要感謝某人幫助我修復我的代碼。然而,程序現在在進入Matrix B的元素後崩潰了。另外,這非常奇怪,但是在輸入任意矩陣的列數之後,程序允許我繼續輸入更多的值在提示我輸入矩陣的元素之前。當我輸入矩陣的值時,爲什麼我的程序崩潰?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int x,y,i,j,m,n;
vector<vector<int> > A;
vector<vector<int> > B;
vector<vector<int> > C;
cout<<"Enter the number of rows for Matrix A: "<<endl;
cin>>x;
cout<<"Enter the number of rows for Matrix B: "<<endl;
cin>>y;
//dynamically resizeable array of dynamically resizeable arrays
A.resize(x); // allocate storage for x dimension.
for (i = 0; i < x; i++)
{
A[i].resize(y); // allocate storage for y dimension for this one x
for (j = 0; j < y; j++)
{
cin >> A[i][j];
}
cout << endl;
}
cout<<"\n\nEnter the elements of Matrix A: "<<endl;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
cin>>A[i][j];
}
cout<<endl;
}
cout<<"\n\nMatrix A :\n\n";
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
cout<<"\t"<<A[i][j];
}
cout<<endl;
}
cout<<"********************************************************"<<endl;
cout<<"Enter the number of rows for Matrix B: "<<endl;
cin>>m;
cout<<"Enter the number of columns for Matrix B: "<<endl;
cin>>n;
B.resize(m); // allocate storage for x dimension.
for (i = 0; i < m; i++)
{
B[i].resize(n); // allocate storage for y dimension for this one x
for (j = 0; j < n; j++)
{
cin >> A[i][j];
}
cout << endl;
}
cout<<"\n\nEnter elements for Matrix B :\n\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>B[i][j];
}
cout<<endl;
}
cout<<"\n\nMatrix B :\n\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<"\t"<<B[i][j];
}
cout<<endl;
}
if(y==m)
{
for(i=0;i<x;i++)
{
for(j=0;j<n;j++)
{
C[i][j]=0;
for(int k=0;k<m;k++)
{
C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
}
}
cout<<"*******************************************************"<<endl;
cout<<"\n\nMultiplication of Matrix A and Matrix B: \n\n";
for(i=0;i<x;i++)
{
for(j=0;j<n;j++)
{
cout<<"\t"<<C[i][j];
}
cout<<endl;
}
}
else
{
cout<<"\n\nMultiplication is not possible"<<endl;;
}
system("pause");
return 0;
}
當然,你的意思是「我的程序崩潰」......你的程序只有10×10的矩陣空間。猜猜你有20×1矩陣會發生什麼? – lmz
這是編譯的程序或編譯器崩潰? – SleuthEye
說編譯器崩潰使得它聽起來像編譯器本身有一個錯誤,因爲編譯器在構建程序時不應該真正「崩潰」 - 它應該成功或告訴你在編寫程序時出現錯誤。但是就像其他評論者所說的那樣,這聽起來像是你編譯成功後的程序在編譯後以特定的方式運行時會崩潰。 –