C++ primer plus第六版课后编程题答案9.4


SALES.h

#ifndef SALES_H_
namespace SALES
{
	const int QUARTERS=4;
	struct Sales{
		double sales[QUARTERS];
		double average;
		double max;
		double min;
	};
	void setSales(Sales &s,const double ar[],int n);
	void setSales(Sales &s);
	void showSales(const Sales &s);
} 




#endif

SALES.cpp

#include "SALES.h"
#include <iostream>
static int count=0;//用于记录数组有多少个元素
using  std::cout;
using std::cin;
using std::endl;
namespace SALES
{
	
	void setSales(Sales &s,const double ar[],int n)
	{
		count=n;
		double Avg,Max,Min,Sum=0;
		if(n>4)	//如果N>4,令N=4
			n=4;
		if(n==0)
		{
			s.average=0;
			s.max=0;
			s.min=0;
		}
		if(n<=4&&n>0)
		{
			count=n;
			Avg=Max=Min=ar[0];
			for(int i=0;i<n;i++)
			{
				s.sales[i]=ar[i];
				Sum+=s.sales[i];
				if(s.sales[i]>Max)
					Max=s.sales[i];
				if(s.sales[i]<Min)
					Min=s.sales[i];
			}
			Avg=Sum*1.0/n;
			s.average=Avg;
			s.max=Max;
			s.min=Min;	
		}

	
	
	}
	void setSales(Sales &s)
	{
		double Max,Min,Avg;
		Max=-999;	//必须适当初始化
		Min=9999;
		Avg=0;
		double Sum=0;
		for(int i=0;i<QUARTERS;i++)
		{
			cout<<"Please enter the valus:"<<endl;
			cin>>s.sales[i];
			Sum+=s.sales[i];
				if(s.sales[i]>Max)
					Max=s.sales[i];
				if(s.sales[i]<Min)
					Min=s.sales[i];	
		}
			Avg=Sum*1.0/QUARTERS;
			s.average=Avg;
			s.max=Max;
			s.min=Min;
			count=QUARTERS;	//令count=4
	}
	void showSales(const Sales &s)
	{
		cout<<"show Sales:"<<endl;
		cout<<"s.sales address="<<s.sales<<endl;
		
		//cout<<sizeof(s.sales)<<endl;
		//cout<<sizeof(double)<<endl;
		//int count=0;//检测数组元素个数
		//for(int i=0;s.sales[i]!='\0';i++)	//不要试图用这个来检测数组元素个数,你可以调试一下就能发现
		//{//Tips:数组空元素地址内原有的数值不一定为'\0'
			//cout<<s.sales[i]<<endl;		
			//count++;
		//}
		cout<<"count="<<count<<endl;
		for(int i=0;i<count;i++)
			cout<<s.sales[i]<<"  ";
		cout<<"\nmax is :"<<s.max<<endl;
		cout<<"Min is :"<<s.min<<endl;
		cout<<"Avg is "<<s.average<<endl;
		cout<<"show end;"<<endl<<endl;
	
	
	}


}

main94.cpp

#include <iostream>
#include "SALES.h"
using namespace std;
//using namespace SALES;
void main94()
{
	using SALES::Sales;
	Sales s1;
	Sales s2;
	double arr[7]={5.2,6.3,4.1,2.5,3.0,4.2,7.5};
	using SALES::setSales;
	setSales(s1,arr,6);
	showSales(s1);
	setSales(s2);
	showSales(s2);
	system("pause");




}

 

 

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注