• C语言之文件操作04——输入矩阵a,b,求乘积c,并打印a,b,c到文件


    //文件与数组结合
    /*
    =================================================================
    题目:输入矩阵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相同理解就可以!


    ========================================================================
    */




  • 相关阅读:
    THUSC2018退役预定
    TAT
    dsu on tree(CF600E Lomsat gelral)
    Bzoj4784: [Zjoi2017]仙人掌
    [APIO2018] Duathlon 铁人两项
    仙人掌基础
    Bzoj3672: [Noi2014]购票
    CF809E Surprise me!
    虚树(Bzoj3611: [Heoi2014]大工程)
    Bzoj3197: [Sdoi2013]assassin
  • 原文地址:https://www.cnblogs.com/yfceshi/p/6972577.html
Copyright © 2020-2023  润新知