自创原题1:投资是当代必需的理财手段,现要做一个多文件小程序,记录每个月的基金收益,并且能计算出平均值、月收益的最大值以及最小值。
要求:1.头文件中使用名字空间 2. 源代码文件中定义使用内部静态链接的函数求最大值和最小值以及平均值的函数 3.尽可能使用相关课程知识。
//fund.h
#ifndef FUND_H_
#define FUND_H_
namespace Jeff
{
const int MONTH =6; //与类区别开来。
struct fund
{
double profit[MONTH]={0};
double average;
double max;
double min;
};
void loadData(fund& f, const double ar[],int n);
void loadData(fund& f);
void showFund(const fund& f);
}
#endif
//源代码1.cpp
#include<iostream>
#include"fund.h"
using namespace std;
namespace Jeff
{
static double MAX(const fund& f)
{
double temp=-1000000;
int i=0;
for(;i<MONTH;i++)
{
if(temp<f.profit[i])
temp=f.profit[i];
}
return temp;
}
static double MIN(const fund& f)
{
double temp=1000000;
int i=0;
for(;i<MONTH;i++)
{
if(temp>f.profit[i])
temp=f.profit[i];
}
return temp;
}
static double AVER(const fund&f)
{
double total=0;
int i=0;
for(;i<MONTH;i++)
{
total+=f.profit[i];
}
return total/MONTH;
}
void loadData(fund& f,const double ar[],int n)
{
int i=0;
int times = n>MONTH?MONTH:n;
for(;i<times;i++)
{
f.profit[i]=ar[i];
}
f.max =MAX(f);
f.min =MIN(f);
f.average =AVER(f);
}
void loadData(fund& f)
{
int i=0;
cout<<"\n手动输入当月获利金额:\n";
for(;i<MONTH;i++)
{
cin>>f.profit[i];
}
f.max =MAX(f);
f.min =MIN(f);
f.average =AVER(f);
}
void showFund(const fund& f)
{
int i=0;
for(;i<MONTH;i++)
{
cout<<"Month "<<i+1<<" : "<<f.profit[i]<<endl;
}
cout<<"The most profitable month you earn: "<<f.max <<endl;
cout<<"The most poor month you earn: "<<f.min <<endl;
cout<<"The average of 6 month is : "<<f.average <<endl;
}
}
//源代码2.cpp
#include<iostream>
#include"fund.h"
using namespace std;
int main()
{
using namespace Jeff;
double ar[MONTH]={0,-14.06,-308.72,214.25,-58.99,855.50};
fund f1,f2;
loadData(f1,ar,6);
showFund(f1);
loadData(f2);
showFund(f2);
return 0;
}
输出结果:
自命题1输出结果
要注意的地方:
- 头文件中有名称空间,源代码文件中定义也需要名称空间。
- 源代码文件中书写定义,可以在名称空间中使用static来声明定义新函数(头文件中没有的函数)