算法竞赛入门经典_2.4_算法竞赛中的输入输出框架

  很久没写博客了,我偷奶(懒)了这个月.

今天的一节是算法竞赛中的输入输出框架,比较实用.

  •   我们先看一个demo
#include "stdio.h"
//数据统计 2017-8-14
#define LOCAL
#define INF 1000000000
int main(int argc, char* argv[])
{
#ifdef LOCAL
    //重定向输入输出
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

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

  • 通过freopen进行重定向输入输出,这样输入流和输出流就保存在文件里了,不过要注意的是,有些算法竞赛中入过要求不可以用重定向的方式,那么我们就得使用fopen了,下面再看一个demo
  • 注意在输出为double类型的时候,做除法或其它运算时,要在前面加(double)进行强制转换,否则会输出整数
#include <stdio.h>

#define INF 1000000000
int main(int argc, char* argv[])
{
    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
", max, min, (double)s / n);

    fclose(fin);
    fclose(fout);
    return 0;
}

运行输入结果差不多,这里就不给截图了,后者就没有使用重定向

 注意:

  1. 在Windows中输入完毕后,先按Enter ,再按ctrl + z最后再按Enter结束输入
  2. 在Linux中ctrl + d可以直接结束输入
  3. 变量在为赋值前,值是不确定的,特别的,不一定等于0
  4. scanf函数返回成功输入的变量个数
  5. 在算法比较大小中可以进行假象无穷大:如:INF = 1000000000,max = -INF, min = INF,也可以先读取值,在赋值,max = min = x
  6. 在算法竞赛中,选手应严格遵守比赛的文件名规定,包括程序文件名和输入输出文件名,不要弄错大小写,不要使用绝对和相对路径
原文地址:https://www.cnblogs.com/ncgds/p/7361974.html