📄 气象信息.cpp
字号:
//天气
#include<stdlib.h> //exit()函数的定义
#include<iostream.h>
#include<fstream.h> //IO所需库
#define FILE_IN "weather.in"
#define FILE_OUT "report.out"
float FindAve(float[],int);
void HighLow(float[],float[],float*,float*,int);
void main()
{
float high[31],low[31],high_ave,low_ave,hottest,coldest;
char date[25],location[100];
int total_days,i=0;
//先定义输入输出流
ifstream input; //输入流对象
ofstream output; //输入流对象
//打开文件用于读数据,如果文件不在,不要创建文件
input.open(FILE_IN,ios::in|ios::nocreate);
//检查文件是否打开。另外一种方法是利用fail函数
if(!input)
{
cout<<"\n未找到输入文件"<<FILE_IN;
cout<<"\n退出程序,再见!\n";
exit(1);
}
output.open(FILE_OUT,ios::out);
cout<<"\n文件找到,继续执行……";
//读入两行,并存入字符串中
input.getline(date,24);
input.getline(location,49);
cout<<location<<endl;
while(!input.eof()) //一直读到文件结束
{
input>>high[i]>>low[i]; //文件指针位置必须无误,不能出现非预期数据
++i;
}
total_days=i-1; //温度记录的天数为i
cout<<"\n读数据完毕"<<endl;
high_ave = FindAve(high,total_days);
low_ave = FindAve(low,total_days);
HighLow(high,low,&hottest,&coldest,total_days);
//向输出文件写数据
output<<"Monthly Weather Report\n\nLocation:\t"<<location
<<"\nDate:"<<date;
output<<"\n\nAverage Temperatures:High "<<high_ave
<<", low "<<low_ave;
output<<"\n\nHottest Temperature:\t"<<hottest
<<"\nColdest Temperature:\t"<<coldest;
input.close();
output.close();
}
float FindAve(float x[],int total)
{
float sum=0.0;
int i;
for(i=0;i<total;++i)
{
sum+=x[i];
}
return (sum/total);
}
void HighLow(float high[],float low[],float *h,float *l,int total)
{
*h=high[0],*l=low[0];
int i;
//遍历两个数组,寻找最大值……
for(i=0;i<total;++i)
{
if(high[i]>*h)*h=high[i];
if(low[i]<*l)*l=low[i];
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -