编辑:该问题的更好解决方案是:
#include<stdio.h>
#include<math.h>
#define NCOL1 2
#define NCOL2 2
#define NROW1 2
#define NROW2 2
#define NCOL3 2
#define NROW3 2
void addarray(double a[NROW1][NCOL1], double b[NROW1][NCOL1], double (*c)[NCOL1]);
int main(void)
{
//Initiate variables
double a,b;
int i,j;
double ans;
double arr1[NCOL1][NROW1], arr2[NCOL2][NROW1];
double arrsum[NCOL1][NROW1];
//Ask user to enter numbers for the first matrix
printf("Please enter numbers for Matrix 1 :\n ");
for(i=0;i<NCOL1;i++){
for(j=0;j<NROW1;j++){
scanf("%lf",&arr1[i][j]);
}
}
//Ask user to enter numbers for the second matrix
printf("Please enter numbers for Matrix 2 :\n ");
for(i=0;i<NCOL2;i++){
for(j=0;j<NROW2;j++){
scanf("%lf",&arr2[i][j]);
}
}
addarray( arr1, arr2, &arrsum[0] );
printf("Output of added arrays\n");
for(i=0;i<NCOL3;i++){
for(j=0;j<NROW3;j++){
printf("%lf ", arrsum[i][j]);
}
printf("\n");
}
return 0;
}
void addarray(double a[NROW1][NCOL1], double b[NROW1][NCOL1], double (*c)[NCOL1])
{
int i,j;
for(i=0;i<NCOL3;i++)
{
for(j=0;j<NROW3;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
但是,只需进行最小的更改,以下内容也将起作用。
看起来 addarray() 正在将其结果放入一个名为 arrsum[][] 的本地矩阵中。要使该程序正常工作,您很可能希望将 arrsum[][] 提供给程序的其余部分(尽管全局数组不是一个好主意)。
在不测试或编译代码的情况下,您至少应该进行以下更改:
1-double arrsum[NCOL3][NROW3];
从addarray()
void addarray(double a,double b)
{
int i,j;
for(i=0;i<NCOL3;i++){
for(j=0;j<NROW3;j++){
arrsum[i][j]=a+b;
}
}
2-arrsum[][]
全球化
#include<stdio.h>
#include<math.h>
#define NCOL1 2
#define NCOL2 2
#define NROW1 2
#define NROW2 2
#define NCOL3 2
#define NROW3 2
/**** add declaration of arrsum[][] here ****/
double arrsum[NCOL3][NROW3];
我已经重写了部分程序,编译并测试了它。新代码如下。
#include<stdio.h>
#include<math.h>
#define NCOL1 2
#define NCOL2 2
#define NROW1 2
#define NROW2 2
#define NCOL3 2
#define NROW3 2
void addarray(double a,double b);
double arrsum[NCOL3][NROW3];
int main(void)
{
//Initiate variables
double a,b;
int i,j;
double ans;
double arr1[NCOL1][NROW1], arr2[NCOL2][NROW1];
//Ask user to enter numbers for the first matrix
printf("Please enter numbers for Matrix 1 :\n ");
for(i=0;i<NCOL1;i++){
for(j=0;j<NROW1;j++){
scanf("%lf",&arr1[i][j]);
}
}
//Ask user to enter numbers for the second matrix
printf("Please enter numbers for Matrix 2 :\n ");
for(i=0;i<NCOL2;i++){
for(j=0;j<NROW2;j++){
scanf("%lf",&arr2[i][j]);
}
}
//Iterate through void function and print out result
for(i=0;i<NCOL3;i++){
for(j=0;j<NROW3;j++){
addarray(arr1[i][j],arr2[i][j]);
// printf("%lf",ans);
}
}
printf("Output of added arrays\n");
for(i=0;i<NCOL3;i++){
for(j=0;j<NROW3;j++){
printf("%lf ", arrsum[i][j]);
}
printf("\n");
}
return 0;
}
void addarray(double a,double b)
{
int i,j;
for(i=0;i<NCOL3;i++){
for(j=0;j<NROW3;j++){
arrsum[i][j]=a+b;
}
}
}