算法竞赛入门经典ch2_ex_2_5最小值、 最大值和平均值

题目

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

样例输入:

2 8 3 5 1 7 3 6

样例输出:

1 8 4.375

要点

  • 输入个数不定

code

#include "stdio.h"

int main()
{
    int n=0, x, min, max, s=0;
    while (scanf("%d", &x))
    {
        if (0 == n)
        {
            min = x;
            max = x;
        }
        s += x;
        if (x > max) max = x;
        if (x < min) min = x;
        ++n;
    }
    printf("%d %d %.3f
", min, max, double(s) / n);
    return 0;
}
  • scanf函数有返回值?

    对,它返回的是成功输入的变量个
    数,当输入结束时,scanf函数无法再次读取x,将返回0。

  • 输入结束

    Windows下,Ctrl+D键,再按Enter键,即可结束输入。

参考code

//**********数据统计(重定向版)**************
#define LOCAL
#include <stdio.h>
#define INF 1000000000

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;

        n++;
    }
    printf("%d %d %.3f
", min, max, (double)s/n);
    return 0;
}

有经验的选手往往会使用条件编译指令并且将重要的测试语句注释掉而非删除。

//**********数据统计(fopen版)**************
#include <stdio.h>
#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;
}

如果想把fopen版的程序改成读写标准输入输出,只需赋值“fin=stdin;fout=stdout;”即可,不要调用fopen和fclose

原文地址:https://www.cnblogs.com/shanchuan/p/8150306.html