首页 > 解决方案 > 添加 3*3 矩阵的代码有什么错误?

问题描述

#include <iostream>

using namespace std;

int main()
{
   int a[3][3] = {1,1,1,1,1,1,1,1,1};
   int b[3][3] = {1,1,1,1,1,1,1,1,1};
   int c[3][3];
   for(int i=1;i<=3;i++)
   {
       for(int j=1;j<=3;j++)
       {
           c[i][j]=a[i][j]+b[i][j];
           cout<<"Element of C"<<i<<j<<"is\t"<<c[i][j]<<endl;
       
       }
  
   
   }

       return 0;

}

在上面的代码中,我在 A22 之前得到了正确的输出,但在上面它给我一个垃圾值。

标签: c++

解决方案


您需要从 0 开始索引矩阵,而不是 1。因此,您需要将for循环更改为for(int i=0;i<3;i++).


推荐阅读