c++ - 如何在 C/C++ 中对二维数组求和

标签 c++ c arrays

我无法在 c 中添加两个二维数组 可能是什么问题 ?我试图从用户输入添加两个多维数组,但输出不正确。 下面是我的代码

#include<stdio.h>
#include<conio.h>
void main()
{
     int m,n,p,q,c,d,k;
     int first[10][10],second[10][10],sum[10][10];
     clrscr();
     printf("\nEnter the number of rows and columns of the first matrix");
     scanf("%d %d",&m,&n);
     printf("\nEnter the elements of the first matrix");
     for (c = 0;c < m;c++)
         for (d = 0;d < n;d++)
             scanf("%d",&first[c][d]);
     printf("\nEnter the number of rows and columns of the second matrix");
     scanf("%d %d",&p,&q);
     printf("\nEnter the elements of the second matrix");
     for (c = 0;c < p;c++)
         for (d = 0;d < p;d++)
             scanf("%d",&second[c][d]);
     for (c = 0;c < m;c++)
         for (d = 0;d < n;d++)
             for (k = 0;k < p;k++)
             {
                  sum[c][d] = first[c][k] + second[k][d];
             }
     printf("\nThe sum of the two matrices is : \n\n");
     for (c = 0;c < m;c++)
         for (d = 0;d < n;d++)
         {
              printf("%d",&sum[c][d]);
              if (d == n-1)
              {
                  printf("\n\n");
              }
         }
     getch();
}

最佳答案

更改此:

for (d = 0;d < p;d++)

对此:

for (d = 0;d < q;d++)

当您填充第二个数组时,因为您使用第一个维度而不是第二个维度。

<小时/>

更改此:

printf("%d", &sum[c][d]);

对此:

printf("%d", sum[c][d]);

因为你想打印一个整数。

<小时/>

PS:这是 C,不是 C++。

关于c++ - 如何在 C/C++ 中对二维数组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53169864/

相关文章:

java - java.util.Arrays 如何处理 ArrayList 的排序(长度与大小)?

java - 二维数组的列和

c++ - 为什么我不能用 c = new (char*)[10] 初始化 char** c,而 c = new char*[10] 可以?

c++ - 将 if else 语句的最后一个值赋给变量

c++ - 区分指针和数据变量

c++ - malloc 中的段错误 :

c++ - 简单的文档切换器功能?

c - 如何从文件中逐行读取

c - 如何将 ASCII 转换为十六进制,反之亦然?

c++ - 如何修复 C++ 中的 'Heap has been corrupted ' 错误?