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"); }
——————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:https://www.royalchen.com/
author:royalchen
Email:royalchen@royalchen.com
———————————————————————————————————————————————————