|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一世轻尘 于 2020-12-27 11:22 编辑
- #include<stdio.h>
- #include<stdlib.h>
- int main()
- {
- FILE*fp;
- float num;
- int n,i,ch2;
- float ch,ch1;
- if((fp=fopen("studentGrades.txt","w"))==NULL)
- {
- printf("error\n");
- exit(0);
- }
- printf("请输入你要写入的数据的个数:\n");
- scanf("%d",&n);
- for(i=0;i<n;i++)
- {
- scanf("%f",&ch);
- fprintf(fp,"%f",ch);
- }
- fclose(fp);
- if((fp=fopen("studentGrades.txt","r"))==NULL)
- {
- printf("error\n");
- exit(0);
- }
- while(!feof(fp))
- {
- fscanf(fp,"%f",&ch1);
- num+=ch1;
- }
- num=num/4;
- printf("%.2f",num);
- fclose(fp);
- return 0;
- }
复制代码
为啥只读第一个数鸭
本帖最后由 jackz007 于 2020-12-27 12:03 编辑
两个问题:
1、数据之间必须有空格
2、一行数据的末尾必须要有换行符
- #include<stdio.h>
- int main()
- {
- FILE * fp ;
- float num ;
- int c , n , i , ch2 ;
- float ch , ch1 ;
- if((fp = fopen("studentGrades.txt" , "w")) != NULL) {
- printf("请输入你要写入的数据的个数 : ") ;
- scanf("%d" , & n) ;
- printf("请输入你要写入的数据 : ") ;
- for(i = 0 ; i < n ; i ++) {
- scanf("%f" , & ch) ;
- if(! (i % 10)) {
- if(i) fprintf(fp , "\n") ; // 每行 10 个数,行末写回车
- } else {
- fprintf(fp , " ") ; // 数据之间要有空格
- }
- fprintf(fp ,"%.6f",ch) ;
- }
- fprintf(fp ,"\n") ; // 最后一个数写完一定要带回车
- fclose(fp) ;
- if((fp = fopen("studentGrades.txt" , "r")) != NULL) {
- num = c = 0 ;
- fscanf(fp , "%f" , & ch1) ; // 循环前先一定要先读一次
- while(! feof(fp)) {
- c ++ ;
- num += ch1 ;
- fscanf(fp , "%f" , & ch1) ;
- }
- fclose(fp) ;
- if(c) num /= c ;
- printf("%.6f\n" , num) ;
- } else {
- fprintf(stderr , "无法为读而打开文件.\n") ;
- }
- } else {
- fprintf(stderr , "无法为写而打开文件.\n") ;
- }
- }
复制代码
|
-
|