我正在尝试编写一个C程序来查找中间三行中元素的总和是否等于矩阵打印的中间三列中元素的总和 . 到目前为止,我能够找到矩阵中所有列和行的总和 .
#include<stdio.h>
void main()
{
static int array[10][10];
int i, j, m, n,sum = 0;
printf("Enter the order of the matrix\n");
scanf("%d %d", &m, &n);
if (m>=5&& n>=5)
{
printf("Enter the elements of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + array[i][j] ;
}
printf("Sum of the %d row is = %d\n", i, sum);
sum = 0;
}
sum = 0;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
sum = sum + array[i][j];
}
printf("Sum of the %d column is = %d\n", j, sum);
sum = 0;
}
}
else
{
printf("The matrix should be a 5 by 5 or bigger");
}
}
3 回答
试试这个
我们假设该数组有n行和m列 . 在这种情况下,您可以通过以下方式计算中间三行和列的总和
这是一个示范计划
输出是
现在您需要的是提供数组的适当尺寸和数据的用户输入 .
在您的代码中,您要求用户输入
row and column count
,但您已经决定了这一点,而且您无法使用用户输入动态创建array
. 但是,有一些方法可以根据用户请求创建数组,我们有Dynamic Memory Allocation
概念来拯救 . 暂时使用预定义的大小 .How to get row Data
在c中,您必须将行固定为
i
,array[i][j]
i
为行且j
为列引用,并循环j
以获取所有行元素值How to get Column Data
与上面相同,循环
i
并修复j
,正好相反 .