//文件与数组结合
/*
=================================================================
题目:输入矩阵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("文件打开失败!\n");
else
{
//输入矩阵a
printf("矩阵a(%dx%d):\n",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",N,M);
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
scanf("%d",&b[i][j]);
}
system("cls");
//输出矩阵a
printf("a=\n");
fprintf(fp,"a=\n");
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,"\n");
printf("\n");
}
//输出矩阵b
printf("b=\n");
fprintf(fp,"b=\n");
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,"\n");
printf("\n");
}
//计算矩阵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=\n");
fprintf(fp,"c=a*b=\n");
for(i=0;i<M;i++)
{
for(j=0;j<M;j++)
{
printf("%3d ",c[i][j]);
fprintf(fp,"%3d ",c[i][j]);
}
printf("\n");
fprintf(fp,"\n");
}
}
fclose(fp);
}
/*
========================================================================
评:
将文件fprintf(fp,"%3d",a[i][j])与一般文件printf同样理解即可!
========================================================================
*/
版权声明:博主文章可以被非商用转载,但请务必注明出处,因水平有限,难免出错,在此免责。