1填空题:
#include<math.h>
#include <iostream>
using namespace std;
class loc
{
private:
float x, y;
public:
//(1)
loc(float x1,float y1)
{
x = x1;
y = y1;
}
//( 2 )
static float dis(loc&, loc&);
};
float loc::dis(loc& a, loc& b)
{
float dx = a.x - b.x;
float dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
int main()
{
loc p1(3.5, 4.5), p2(5.5, 6.5);
float d = loc::dis(p1, p2);
cout << "The distance is " << d;
}
//(程序运行结果为: 3 )
//The distance is 2.82843
2结果分析题:
#include <iostream>
using namespace std;
class Test {
private:
static int val;
int a;
public:
static int func();
void sfunc(Test& r);
};
int Test::val = 200;
int Test::func()
{
return val++;
}
void Test::sfunc(Test& r)
{
r.a = 125;
cout << "\nResult3=" << r.a;
}
void main()
{
cout << "Result1=" << Test::func() << endl;
Test a;
cout << "Result2=" << a.func();
a.sfunc(a);
}
运行结果:
Result1=200
Result2=201
Result3=125
3结果分析题:
# include< iostream>
using namespace std;
class M
{
int A;
static int B;
public:
M(int a)
{
A = a;
B += a;
cout << "Constructing " << endl;
}
static void f1(M m);
~M()
{
cout << "Destructing \n";
}
};
void M::f1(M m)
{
cout << "A=" << m.A << endl;
cout << "B=" << B << endl;
}
int M::B = 0;
int main()
{
M P(7), Q(12);
M::f1(P);
M::f1(Q);
return 0;
}
运行结果:
Constructing
Constructing
A=7
B=19
Destructing
A=12
B=19
Destructing
Destructing
Destructing
4编程题:
编写程序,已有若干学生的数据,包括:学号、姓名、某门课的成绩,要求输出这些学生的信息,并计算出学生总人数和平均成绩(要求将学生总人数和总成绩用静态数据成员表示,对静态数据成员的操作用静态成员函数,若干学生对象用对象数组表示,输出学生信息用循环)。
参考运行结果如下:
#include<iostream>
#include<string>
using namespace std;
class student
{
public:
void show()
{
cout <<num<< "\t " <<name<< "\t" <<score<< "\t" << endl;
}
static void show1()
{
cout << "学生总人数为: " << count << endl;
cout << "平均分为: " << aver << endl;
}
student(string num1,string name1,double score1)
{
num = num1;
name = name1;
score = score1;
count++;
sum += score1;
aver = sum / count;
}
private:
string num;
string name;
double score;
static double sum;
static int count;
static double aver;
};
double student::sum = 0.0;
int student::count = 0;
double student::aver = 0.0;
int main()
{
student stu[4] = { student("2019001","张三",78)
,student("2019105","李四",85)
,student("2019128","王五",67)
,student("2019341","赵六",75) };
cout << "学号\t " << "姓名\t" << "成绩\t" << endl;
for (int i = 0; i < 4; i++) {
stu[i].show();
}
stu->show1();
return 0;
}