//文件与数组结合
/*
=================================================================
题目:输入矩阵a,b,求乘积c,并打印a,b,c到D盘文件x.txt,并在屏幕显示。
说明:必须满足a的列=b的行。
=================================================================
*/
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3
void main()
{
FILE *fp;
int a[M][N],b[N][M],c[N][N];
int i,j,k=0;
fp=fopen("D:\x.txt","w");
if(fp==NULL)
printf("文件打开失败!
");
else
{
//输入矩阵a
printf("矩阵a(%dx%d):
",M,N);
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
scanf("%d",&a[i][j]);
}
//输入矩阵b
printf("矩阵b(%dx%d):
",N,M);
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
scanf("%d",&b[i][j]);
}
system("cls");
//输出矩阵a
printf("a=
");
fprintf(fp,"a=
");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
printf("%3d ",a[i][j]);
fprintf(fp,"%3d ",a[i][j]);
}
fprintf(fp,"
");
printf("
");
}
//输出矩阵b
printf("b=
");
fprintf(fp,"b=
");
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("%3d ",b[i][j]);
fprintf(fp,"%3d ",b[i][j]);
}
fprintf(fp,"
");
printf("
");
}
//计算矩阵c
for(i=0;i<M;i++)
{
for(j=0;j<M;j++)
{
c[i][j]=0;
for(k=0;k<N;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
//输出矩阵c
printf("c=
");
fprintf(fp,"c=a*b=
");
for(i=0;i<M;i++)
{
for(j=0;j<M;j++)
{
printf("%3d ",c[i][j]);
fprintf(fp,"%3d ",c[i][j]);
}
printf("
");
fprintf(fp,"
");
}
}
fclose(fp);
}
/*
========================================================================
评:
将文件fprintf(fp,"%3d",a[i][j])与一般文件printf相同理解就可以!
========================================================================
*/