zoukankan      html  css  js  c++  java
  • C从文件中加载矩阵

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 struct Matrix{
     5     int row;
     6     int col;
     7     int *mat;
     8 };
     9 /*初始化一个r行c列的矩阵*/
    10 struct Matrix matrix_initialize( int r, int c )
    11 {
    12     struct Matrix m;
    13     m.row = r;
    14     m.col = c;
    15     (m.mat) = (int *) malloc( sizeof(int)*(m.row)*(m.col));
    16     return m;
    17 }
    18 
    19 /*打印矩阵到标准输出*/
    20 void matrix_show( struct Matrix m )
    21 {
    22     int i,j;
    23     for( i = 0; i<m.row; i++)
    24     {
    25         for(j = 0; j<m.col; j++)
    26         {
    27             printf("%d ",*(m.mat+i*(m.col)+j) );
    28         }
    29         printf("
    ");
    30     }
    31 } 
    32 
    33 /*从文件加载矩阵,文件第一行为矩阵的行值和列值,以后为数据(int型)*/
    34 struct Matrix* load( char *file_name, struct Matrix * pm )
    35 {
    36     FILE *fp;
    37     if( !(fp = fopen( file_name, "r" ) ) )
    38         exit(-1);
    39     //struct Matrix *pm;
    40     printf("loading file %s...
    ",file_name);
    41     fscanf(fp,"%d%d",&(pm->row),&(pm->col));
    42     pm->mat = (int *) malloc(sizeof(int)*(pm->row)*(pm->col));
    43     int i,j;
    44     for(i=0;i<pm->row;i++)
    45     {
    46         for(j = 0; j < pm->col; j++)
    47         {
    48             if( fscanf(fp,"%d",((pm->mat)+i*(pm->col)+j)) == EOF )
    49                 exit(-1);
    50         }
    51     }
    52     fclose(fp);
    53     return pm;
    54 }
    55 
    56 
    57 int main()
    58 {
    59     struct Matrix m;
    60     struct Matrix *pm = &m;
    61     pm = load("matrix.dat",pm);
    62     matrix_show(*pm);
    63     return 0;
    64 }
  • 相关阅读:
    渚漪Day18——JavaWeb 09【JSP】
    渚漪Day17——JavaWeb 08【Session】
    渚漪Day16——JavaWeb 07【Cookie】
    渚漪Day15——JavaWeb 06【HTTPServletRequest】
    渚漪Day14——JavaWeb 05【HTTPServletResponse】
    Typora编写markdown 常用入门
    Vue 笔记
    ABCNN 学习笔记
    DSSM 学习笔记
    支持向量机 SVM 学习笔记
  • 原文地址:https://www.cnblogs.com/yongjiuzhizhen/p/4305203.html
Copyright © 2011-2022 走看看