讨论文件输入输出

 输入不超过1000的若干整数,输出最大、最小、平均值:

关键在于,输入数字个数是不确定的

一,利用scanf函数的返回值就是返回输入数字的个数,的,这个特性判断输入终止。

#include"iostream"
#include"ctime"
using namespace std; 

int main()
{
    int x,n=0,min,max,s=0;
    while(scanf("%d",&x)==1){
        s+=x;
        if(x<min)min=x;
        if(x>max)max=x;
        ++n;
    } 
    printf("%d %d %d",min,max,(double)s/n);
    return 0;
}

这样子做可以输入无限多的数,但问题是,如何结束输入呢?

enter+ctrl z+enter可以结束输入.

另外值得注意的是,定义min与max时并未赋初值,如果直接将他们输出,会看出此时他们的值其实是任意的;所幸的是,我的电脑上min=41,max=0,还比较靠谱;如果min随机到了-100000,max随机到了100000,在这种情况下,当我们输入的数据都既不太小又不太大时,最大最小值就都得不到正确答案。

所以最好还是为min与max赋初值,例如定义INF=2147483648(2^32),max=-INF,min=INF-1.

二,利用文件读写

1.输入输出重定向:在main函数入口处加:

freopen("intput.txt","r",stdin);
freopen("output.txt","w",stdout);

这样,scanf函数将从input.txt中读入,printf写入文件output.txt。这样子一个巨大的好处就是,当题目需要输入很多数字,你一遍遍的验证自己的程序是否正确时,再也不用一遍遍的输入了,剩下好多时间!

但是,有些比赛不允许通过文件重定向来读写文件,这时可以用“开关”来控制是否使用文件重定向。

当定义了LOCAL,就执行 #ifdef LOCAL 与 #endif 之间的语句,因此,在提交时删除掉#define LOCAL即可。这使得我们可以继续享受输入输出重定向带来的便捷。

另还,还可以在编译选项里定义这个LOCAL符号,参考紫书附录A

#define LOCAL
#include"iostream"
#include"ctime"
using namespace std; 

int main()
{
    #ifdef LOCAL
    freopen("intput.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
    int x,n=0,min,max,s=0;
    while(scanf("%d",&x)==1){
        s+=x;
        if(x<min)min=x;
        if(x>max)max=x;
        ++n;
} printf(
"%d %d %d",min,max,(double)s/n); return 0; }

2.当比赛要求一定要用文件输入输出,但禁止用重定向的方式时,程序如下

阅读程序可了解具体语法

#include"iostream"
#include"ctime"
using namespace std; 

#define INF 1000000000

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
",min,max,(double)s/n);
    fclose(fin);
    fclose(fout);
    return 0;
}

 

柳暗花明又一村
原文地址:https://www.cnblogs.com/ucandoit/p/8229018.html