namereq

csv読込で平均点算出

Jun 18th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. /*
  2. データの書き込みのところでアクセスしてはいけない
  3. メモリにアクセスしていたので、
  4. for文に直しました。基本的には
  5. いじっていません。
  6. */
  7.  
  8. #include<stdio.h>
  9. #include<stdlib.h>
  10. /* ファイルからデータを読み込み、平均点を算出 */
  11. struct student{
  12. int id;
  13. char name[20];
  14. int kokugo;
  15. int sugaku;
  16. int eigo;
  17. };
  18. int main(void){
  19.    
  20.     FILE *fp;
  21.     struct student student1[3];
  22.     int i = 0;
  23.     double ave[3]; //平均点
  24.    
  25.     //ファイルのオープン
  26.     if((fp = fopen("seiseki2.csv", "r")) == NULL){
  27.         printf("error");
  28.         exit(1);
  29.     }
  30.     //データの読み込み
  31.     while((fscanf(fp, "%d,%[^,],%d,%d,%d", &student1[i].id, student1[i].name,
  32.     &student1[i].kokugo, &student1[i].sugaku, &student1[i].eigo)) != EOF){
  33.         i++;
  34.     }
  35.     fclose(fp);
  36.    
  37.     //平均点の計算
  38.     for(i = 0; i < 3; i++){
  39.         ave[i] = (double)(student1[i].kokugo + student1[i].sugaku + student1[i].eigo) / 3;
  40.     }
  41.    
  42.     //ファイルのオープン
  43.     if((fp = fopen("average.txt", "w")) == NULL){
  44.         printf("error");
  45.     exit(1);
  46.     }
  47.     //データの書き込み
  48.     for(i = 0; i < 3; i++){
  49.         fprintf(fp, "%d,%s,%.2lf\n", student1[i].id, student1[i].name, ave[i]);
  50.     }
  51.     fclose(fp);
  52.    
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment