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

标签 c++ matrix sum addition

你好,我正在尝试将 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 。如果您使用比“i”和“j”更长且更不同的变量名称,则此类错误更容易看到,例如“行”与“列”

关于c++ - 新手 - c++ 中的矩阵加法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5209665/

相关文章:

python - 在python中对文件中的整数求和

c++ - 嵌套循环最有可能因为不正确的 bool 运算符而重复自身 C++

C++ 和 PyQt | QCheckBox 的用户定义插槽和连接

sql - TSQL 运行总计根据前一行的总和进行聚合

arrays - 数组到矩阵

matlab - 在不使用 for 循环的情况下将矩阵添加到结构列?

java - 为什么按 Id 对对象列表进行分组仅在该函数中第一次调用时有效?

c++ - 为什么我得到 "declaration is incompatible with (x)"?

c++ - 从编译时 vector 中删除相邻重复项的元程序

python - Numpy:分别给定每个坐标的矩阵来构造点矩阵的替代方法