4、编写一个程序,已有若干学生的数据,包括学号、姓名、成绩,要求输出这些学生的数据并计算出学生人数和平均成绩(要求将学生人数和总成绩用静态数据成员表示)。
#include <iostream>
#include<string>
using namespace std;
class student
{
private:
string name;
string ID;
float score;
static int sum;
static float totalScore;
public:
student( string name1,string ID1,float score1);
static void show(student &stu);
static void show_sum_totalScore();
};
student::student(string name1,string ID1,float score1)
{
name=name1;
ID=ID1;
score = score1;
++sum;
totalScore += score;
}
void student::show(student &stu)
{
cout << "姓名: " <<stu. name <<endl;
cout << "学号: " << stu.ID << endl;
cout << "成绩:"<<stu.score<<endl;
}
void student::show_sum_totalScore()
{
cout<<"总人数:"<<sum<<endl;
cout<<"总成绩:"<<totalScore<<endl;
}
int student::sum=0;
float student::totalScore=0.0;
int main()
{
student stu1("liming",01,80);
student::show(stu1);
student::show_sum_totalScore();
student stu2("lili",02,83);
student::show(stu2);
stu2.show_sum_totalScore();
return 0;
}
4、设计一个点类,其中包含一对坐标点数据成员、一个求两个点之间距离的友元函数dist和显示坐标点的成员函数,并用数据进行测试。
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point(int xx=0, int yy=0)
{X=xx;Y=yy;}
int GetX()
{return X;}
int GetY()
{return Y;}
friend float Dist(Point &a, Point &b);
private:
int X,Y;
};
float Dist(Point &p1, Point &p2)
{ double x=double(p1.X-p2.X);
double y=double(p1.Y-p2.Y);
return float(sqrt(x*x+y*y));
}
void main()
{
Point myp1(1,1),myp2(4,5);
cout<<"The distance is:";
cout<<Dist(myp1,myp2)<<endl;
}