zoukankan      html  css  js  c++  java
  • 2-5*数据统计I

    输入一些整数,求出他们的最小值,最大值,和平均值(保留三位有效小数)。输入这些数都是不超过1000的整数。
    样例输入:
    2 8 3 5 1 7 3 6
    样例输出:
    1 8 4.375

     1 #include<stdio.h>
     2 #define INF 1000000000
     3 int main()
     4 {
     5 FILE *fin,*fout;
     6 fin=fopen("in.txt","rb");
     7 fout=fopen("out_2.txt","wb");
     8 int x,n=0,min=INF,max=-INF,s=0;
     9 while(fscanf(fin,"%d",&x)==1)
    10 {
    11 s+=x;
    12 if(x<min)
    13 min=x;
    14 if(x>max)
    15 max=x;
    16 n++;
    17 }
    18 fprintf(fout,"%d  %d  %.3f",min,max,(double)s/n);
    19 fclose(fin);
    20 fclose(fout);
    21 return 0;
    22 }
     1 #include<stdio.h>
     2 #define LOCAL
     3 #define INF 1000000000
     4 int main()
     5 {
     6 #ifdef LOCAL
     7 freopen("in.txt","r",stdin);
     8 freopen("out_1.txt","a",stdout);
     9 #endif
    10 int x,n=0,min=INF,max=-INF,s=0;
    11 while(scanf("%d",&x)==1)
    12 {
    13 s+=x;
    14 if(x<min)
    15 min=x;
    16 if(x>max)
    17 max=x;
    18 n++;
    19 }
    20 printf("%d  %d  %.3f",min,max,(double)s/n);
    21 return 0;
    22 }

    in.txt

    1 2 8 3 5 1 7 3 6

    *********************************************************

    重定向freopen

    声明:FILE *freopen( const char *path, const char *mode, FILE *stream ); 

    path: 文件名,用于存储输入输出的自定义文件名。 
    mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。 
    stream: 一个文件,通常使用标准流文件。 

    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    // 文件名 打开格式 stdin标准输入流,默认为键盘
    freopen(
    "out_1.txt","a",stdout);
    //       文件名 打开格式 stdout标准输出流,默认为屏幕
    //    stderr是标准错误流,一般把屏幕设为默认
    #endif

    使用freopen函数可以避免重复输入大量的数据,比如上例中就将要输入的数据存储在"in.txt"内,输出结果则在"out_1.txt"中

    上例中特别处在于:freopen语句在#ifdef和#endif中。这样只要定义了字符才编译两条freopen语句

    #define LOCAL

    若比赛需要标准输入输出,则只要将#define LOCAL注释掉即可

    缺点:输入输出只能到一个文件

    fopen()

    声明:FILE * fopen(char *filename, *type);

    调用: 文件指针名=fopen(文件名,使用文件方式)

    FILE *fin,*fout;
    fin=fopen("in.txt","rb");
    //     文件名  使用方式 fout
    =fopen("out_2.txt","wb");
    //     文件名  使用方式
    /*常见文件使用方式
    r只读
    w创建,只写;若文件不存在,则自动新建;若文件已存在,则删去原文件再新建
    a增补
    b二进制文件
    +读/写
    t文本文件(可省略)*/

    在启用fopen函数时,需要特定的函数fscanf,fprintf对文件操作;

    普通的scanf和printf依然能在命令行界面操作。

    如果需要改成标准输入输出,则

    fin=stdin;
    fout=stdout;
    好奇一切知识的咸鱼<@_@>
  • 相关阅读:
    常用数据结构的应用场景
    数组与链表的对比
    [LeetCode 293] Flip Game
    [Leetcode] Palindrome Permutation 回文变换
    九大排序算法再总结
    query函数的可查询数据
    Column常用的参数
    sqlalchemy的常用字段
    sqlalchemy基本的增删改查
    sqlalchemy映射数据库
  • 原文地址:https://www.cnblogs.com/xybz/p/9979099.html
Copyright © 2011-2022 走看看