fqy131314

项目3(文件流)

从练习2中的num.txt文件读取各个整数, 打印出最大值和最小值, 以及平均值,和.

#include <iostream>
#include <Windows.h>
#include <fstream>

using namespace std;
int main(void)
{
	ifstream stream;
	int max, min, sum = 0;
	int num;
	int n = 0;

	stream.open("num.txt");
	if (!stream.is_open())
	{
		cout << "文件打开失败" << endl;
		exit(1);
	}

	stream >> num;
	n++;
	max = num;
	min = num;
	sum = sum + num;

	while (!stream.eof())
	{
		stream >> num;
		
		stream >> num;

		if (num > max)
		{
			max = num;
		}

		if (num < min)
		{
			min = num;
		}
		sum = sum + num;
		n++;
	}

	cout << "平均值:" << num / n << endl;
	cout << "和:" << sum << endl;
	cout << "最大值:" << max << endl;
	cout << "最小值:" << min << endl;

	system("pause");
	return 0;

}

posted on 2022-09-14 20:35  会飞的鱼-blog  阅读(12)  评论(0)    收藏  举报  来源

导航