自創(chuàng)原題1:投資是當(dāng)代必需的理財(cái)手段,現(xiàn)要做一個(gè)多文件小程序,記錄每個(gè)月的基金收益,并且能計(jì)算出平均值、月收益的最大值以及最小值。
要求:1.頭文件中使用名字空間 2. 源代碼文件中定義使用內(nèi)部靜態(tài)鏈接的函數(shù)求最大值和最小值以及平均值的函數(shù) 3.盡可能使用相關(guān)課程知識(shí)。
//fund.h
#ifndef FUND_H_
#define FUND_H_
namespace Jeff
{
const int MONTH =6; //與類(lèi)區(qū)別開(kāi)來(lái)。
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手動(dòng)輸入當(dāng)月獲利金額:\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;
}
輸出結(jié)果:

自命題1輸出結(jié)果
要注意的地方:
- 頭文件中有名稱(chēng)空間,源代碼文件中定義也需要名稱(chēng)空間。
- 源代碼文件中書(shū)寫(xiě)定義,可以在名稱(chēng)空間中使用static來(lái)聲明定義新函數(shù)(頭文件中沒(méi)有的函數(shù))