标签:
文件输入输出的例子
以输出任意一组数的最大最小值,平均值为例
input:2 8 3 5 1 7 3 6
output:1 8 4.375
1重定向式
如果有#define LOCAL的时候执行#ifdef LOCAL 和#endif之间的语句, 没有定义LOCAL的时候不执行;
两个fopen加在main函数入口处,他将使得scanf从文件input.txt读入,printf写入文件output.txt
#include <stdio.h>
#define LOCAL int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int x, cnt, mi, ma, s; scanf("%d", &x); s = x; mi = x; ma = x; cnt = 1; while(scanf("%d", &x) == 1) { s += x; if(x < mi) mi = x; if(x > ma) ma = x; cnt++; } printf("%d %d %.3f\n", mi, ma, (double)s/cnt); return 0; }
2如果题目中禁止用重定向式输入,那可以采用下面方法
#include <stdio.h> int main() { FILE *fin, *fout; fin = fopen("data.in", "rb"); fout = fopen("data.out", "wb"); int x, cnt, mi, ma, s; fscanf(fin, "%d", &x); s = mi = ma = x; cnt = 1; while(fscanf(fin, "%d", &x) == 1) { s += x; if(x < mi) mi = x; if(x > ma) ma = x; cnt++; } fprintf(fout, "%d %d %.3f\n", mi, ma, (double)s/cnt); fclose(fin); fclose(fout); return 0; }
标签:
原文地址:http://www.cnblogs.com/rain-1/p/4779983.html