文件的使用方式

示例题目:

数据统计

输入一些整数,求出它们的最小值、最大值和平均值(保留3位小数)。输入保证这些书都是不超过1000的整数。

样例输入:

2 8 3 5 1 7 3 6

样例输出:

1 8 4.375

 

1.使用输入输出重定向的方式

#define LOCAL
#include<stdio.h>
#define INF 100000000
int main()
{
    #ifdef LOCAL
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    #endif
    int x, n=0,min=INF,max=-INF,s=0;
    while(scanf("%d",&x)==1)
    {
        s += x;
        if(x<min) min = x;
        if(x>max) max = x;
        /*
        printf("x = %d, min= %d, max= %d\n",x,min,max);
        */
        n++;
    }
    printf("%d %d %.3f\n", min,max,(double)s/n);
    return 0;
    
}

//重定向版本 

 

 

如果比赛要求用文件输入输出,但禁止用重定向的方式,又当如何呢?

#include<stdio.h>
#define INF 100000000
int main()
{
    FILE *fin,*fout;
    fin = fopen("data.in","rb");
    fout = fopen("data.out","wb");
    int x,n=0,min = INF,max=-INF,s=0;
    while(fscanf(fin,"%d",&x)==1){
        s += x;
        if(x<min) min=x;
        if(x>max) max = x;
        n++;
    }
    fprintf(fout,"%d %d %.3f\n",min,max,(double)s/n);
    fclose(fin);
    fclose(fout);
    return 0;
}

//如果比赛要求用文件输入输出,但禁止用重定向方式,可以如上的fopen方式 

 

posted @ 2020-05-12 22:58  Vincent-yuan  阅读(332)  评论(0编辑  收藏  举报