新手 - c ++中的矩阵加法实现

时间:2011-03-06 09:17:05

标签: c++ matrix sum addition

您好我正在尝试将2个矩阵添加到一个新矩阵中(当我逐步运行程序时它会这样做)但由于某些原因,VS 2010在添加后会给出访问错误。< / p>

这是代码。

#include <iostream>
#include <cstdio>
#include <conio>
using namespace std;

class operatii 
{
    typedef double mat[5][5];
    mat ms,m1,m2;
    int x1,x2,y1,y2;
public:
    void preg();
    int cit_val();
    void cit_mat(int&,int&,double[5][5]);
    void suma();
    void afisare(int&,int&,double[5][5]);
};

void operatii::preg()
{
cit_mat(x1,y1,m1);
cit_mat(x2,y2,m2);
suma();
afisare(x1,y1,ms);
}

int operatii::cit_val()
{
int n;
cin>>n;
return n;
}

void operatii::cit_mat(int& x,int& y,double m[5][5])
{
char r;
cout<<"Matrice patratica? Y/N ";
cin>>r;
if ((r=='y')||(r=='Y'))
{
    cout<<"Numar linii si coloane: ";
    x=cit_val();
    y=x;
}
else
{   
    cout<<"Numar linii: ";
    x=cit_val();
    cout<<"Numar coloane: ";
    y=cit_val();
}
for (int i=1;i<=x;i++)
    for (int j=1;j<=y;j++)
        cin>>m[i][j];
}

void operatii::suma()
{
if ((x1==x2)&&(y1==y2))
    for (int i=1;i<=x1;i++)
        for (int j=1;i<=y1;j++)
            ms[i][j]=m1[i][j]+m2[i][j];
else cout<<"Eroare";
}

void operatii::afisare(int& x,int& y,double m[5][5])
{ 
cout<<endl;
for (int i=1;i<=x;i++)
{
    for (int j=1;j<=y;j++)
        cout<<m[i][j];
    cout<<endl;
}
}

void main()
{
operatii matrice;
matrice.preg();
system("PAUSE");
}

任何形式的帮助都会被贬低。

1 个答案:

答案 0 :(得分:6)

数组在c ++中基于0。

for (somevar=1; somevar<=something)的各种变体更改为for (somevar=0; somevar<something)

您正在写入数组的末尾,它会覆盖堆栈返回地址,从而导致返回不可执行的代码,再次导致访问冲突。

此外,

for (int j=1;i<=y1;j++)

我想你想在这里使用j而不是我。如果您使用比“i”和“j”更长且更不同的变量名称,则更容易看到这样的错误,例如“行”和“列”

相关问题