#define n 50
void matread(char *, double [][n], int *, int *);
void matprint(double [][n],int ,int, char);
int matmul(int, int,int,int,int *, int *, double [][n],double [n][n], double [][n]);
void matprintf(double [][n], int, int, char *);
int main(){
int ra,rb,rc,ca,cb,cc,flag;
double a[n][n],b[n][n],c[n][n];
FILE *fp;
fp=fopen("matA.dat","w");
fprintf(fp,"%d %d\n%.2lf %.2lf %.2lf\n%.2lf %.2lf %.2lf\n",2,3,
1.0, 0.0, 4.0, -2.0, 4.0, 1.0);
fclose(fp);
fp=fopen("matB.dat","w");
fprintf(fp,"%d %d\n%.2lf %.2lf %.2lf %.2lf \n%.2lf %.2lf %.2lf %.2lf \n%.2lf %.2lf %.2lf %.2lf\n",3,4,2.0,0.0,5.0, 1.0,4.0,0.0,-6.0,1.0,5.0,1.0,2.0,1.0);
fclose(fp);
matread("matA.dat",a,&ra,&ca);
matprint(a,ra,ca,'A');
matread("matB.dat",b,&rb,&cb);
matprint(b,rb,cb,'B');
flag=matmul(ra,ca,rb,cb,&rc,&cc,a,b,c);
if(flag==0){
printf("\nMatrices A and B are incompatiable for marix multiplication");
}
else{
matprint(c,rc,cc,'C');
matprintf(c,rc,cc,"matC.dat"); \\PROBLEM OCCURS WHEN THIS IS EXECUTED
}
return 0;
}
void matprintf(double c[][n], int row, int col, char *file){
FILE *fp;
int i,j;
fp=fopen(file,"w");
printf(fp,"%d %d\n", row, col);
for(i=0;i<row;++i){
for(j=0;j<col;++j){
fprintf(fp,"%lf ", c[i][j]);
}
printf("\n");
}
}
int matmul(int ra, int ca,int rb,int cb,int *row, int *col,
double a[][n], double b[n][n], double c[][n]){
int i,j,k;
if(ca!=rb) return 0;
else {
*row=ra;
*col=cb;
for(i=0;i<*row;++i){
for(j=0;j<*col;++j){
c[i][j]=0;
for(k=0; k<cb; k++)
c[i][j]+= (a[i][k])*(b[k][j]);
}
}
}
return 1;
}
void matread(char *file, double a[][n], int *row, int *col){
FILE *fp;
int p,q,i,j;
fp=fopen(file,"r");
assert(fp!=NULL);
fscanf(fp,"%d %d", &p, &q);
*row=p;
*col=q;
for(i=0; i<*row; ++i){
for(j=0;j<*col; ++j){
fscanf(fp,"%lf",&a[i][j]);
}
}
}
void matprint(double a[][n],int row,int col, char c){
int i,j;
printf("Matrix %c is\n",c);
for(i=0; i<row; ++i){
for(j=0;j<col; ++j){
printf("%.1lf ", a[i][j]);
}
printf("\n");
}
}
该代码应该首先从各自的数据文件matA.dat和matB.dat中提取矩阵A和B。这些数据文件的第一行包含矩阵大小,其后包含矩阵条目。
这是使用matread();(工作)完成的然后我们使用matprint()打印这两个矩阵; (工作中)
然后应该检查它们是否兼容乘法(仅检查AB)。>>
如果不兼容,则matmul()返回0,如果兼容,则matmul()计算AB,存储在C中并返回1;否则,返回0。 (工作中)
如果也是兼容的,我们现在应该将矩阵C打印到数据文件matC.dat中
现在这是我迷路的地方。
该问题明确要求我使用此方法:matprintf(c,rc,cc,“ matC.dat”);然后自己定义matprintf()。
所以我的问题是,首先,此时在main()中不存在matC.dat,所以我应该如何将其作为文件传递?我应该将它作为字符串传递吗?
请帮助我。
当前使用此代码,我得到了错误:
矩阵产品。c:53:9:警告:传递'FILE *'的指针类型不兼容(aka'struct __sFILE *')转换为'const char *'类型的参数[-Wincompatible-pointer-types]printf(fp,“%d%d \ n”,row,col);^〜/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/stdio.h:170:36:注意:将参数传递给参数int printf(const char * __restrict,...)__printflike(1,2);^产生1条警告。
#define n 50 void matread(char *,double [] [n],int *,int *);无效的matprint(double [] [n],int,int,char); int matmul(int,int,int,int,int *,int *,double [] [n],double [n] [n],double [] [n]);无效...
您正在将fp
传递给printf
; printf
不接受文件参数,但是fprintf
(如您所知)。