簡體   English   中英

新手-C ++中的矩陣加法實現

[英]Newbie - matrix addition implementation in c++

您好,我正在嘗試將2個矩陣的加法編程到一個新矩陣中(並且當我逐步運行該程序時確實如此),但是由於某種原因,VS 2010在執行加法后給了我一個訪問錯誤。

這是代碼。

#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");
}

任何幫助都將不勝感激。

數組在C ++中從0開始。

for (somevar=1; somevar<=something)的各種變體更改為for (somevar=0; somevar<something)

您正在寫完數組的末尾,這將覆蓋堆棧的返回地址,從而導致返回到不可執行的代碼,再次導致訪問沖突。

也,

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

我想你想在這里用j而不是我。 如果您使用比“ i”和“ j”更長且更獨特的變量名,例如“ Line”和“ Column”,則更容易發現此類錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM