hello heaven

【描述】
我们都知道,对于一个表达式可以这么写:1+2-3+4
那我们是否也可以这样想,在对象的层次上能不能也有这样类似的级联(链式)调用来完成这样的功能呢?
例如上边的表达式可以变成如下格式:
Number op(1);
op.add(2).sub(3).add(4)
op.print(); //在一行上输出最终结果:4
注意:本题所涉及的类型均为int型,无需考虑其他类型。
现在你被安排完成这样一个级联调用的功能,给定类Number,请你完成其中的add方法和sub方法,这两个方法分别接受一个int型的参数,此外Number还有一个有参构造函数,接受的参数也是int型,最后你需要实现一个print的方法,用于打印结果。
【输入】
输入在一行中给出三个整数a、b、c,以空格间隔。
【输出】
输出a-b+c的结果。
【输入示例】
1 3 5
【输出示例】
3
(10分)
我的答案:
class Number
{
int p;
public:
Number(int v):p(v){}
Number &add(int v){
p += v;
return *this;
}
Number &sub(int v){
return add((-1)*v);
}
void print(){
cout<<p<<endl;
}
};
题目得分 10
参考答案:
#include
using namespace std;
class Number {
public:
Number();
Number(int value);
Number& add(int num);
Number& sub(int num);
void print();
private:
int value;
};
Number::Number() {//无参构造函数,对象的默认值为0
value = 0;
}
Number::Number(int value) {//有参构造函数
this->value = value;
}
Number& Number::add(int num) {//加法
this->value += num;
return *this;
}
Number& Number::sub(int num) {//减法
this->value -= num;
return *this;
}
void Number::print() {//输出对象的值
cout << value << endl;
}
int main() {
int a, b, c;
cin >> a >> b >> c;
Number n(a);
n.sub(b).add©;
n.print();
return 0;
}

【描述】
①声明并实现一个名为Arc的类,在二维空间中以某一个点为中心,绘制圆弧。Arc类包含私有数据成员p(圆心,Point类型),radius(圆弧半径,double类型);有参构造函数,将圆心、圆弧半径设置为给定的参数;成员函数draw,输出圆心和半径。
②声明并实现一个名为Circle的类,在二维空间中以某一个点为中心,绘制圆。Circle类包含私有数据成员p(圆心,Point类型),radius(圆半径,double类型);有参构造函数,将圆心、圆半径设置为给定的参数;成员函数draw,输出圆心和半径。
③声明并实现一个名为Ellipse的类,在二维空间中以某一个点为中心,绘制椭圆。Ellipse类包含私有数据成员p(圆心,Point类型),xRadius、yRadius(椭圆轴,double类型);有参构造函数,将圆心、椭圆轴设置为给定的参数;成员函数draw,输出圆心和轴。
④声明并实现一个名为Rectangle的类,在二维空间中以某一个点为左上角,绘制矩形。Rectangle类包含私有数据成员p(左上角坐标,Point类型),width、height(矩形宽度和高度,double类型);有参构造函数,将左上角坐标、矩形宽度和高度设置为给定的参数;成员函数draw,输出左上角坐标和宽度、高度。
⑤声明并实现一个名为Mix的类,在二维空间中以某一个点为中心,绘制圆弧、圆、椭圆,以某一个点为左上角,绘制矩形。Mix类包含有参构造函数,将点坐标、圆弧半径、圆半径、椭圆轴、矩形宽度和高度设置为给定的参数;成员函数draw绘制圆弧、圆、椭圆和矩形,调用Arc类、Circle类、Ellipse类、Rectangle类的draw函数,输出相关信息。
Mix类是Arc类、Circle类、Ellipse类、Rectangle类的多继承派生类。
【输入】
没有输入。
【输出】
Drawing an arc: Center(320, 240), radius(100)
Drawing a circle: Center(320, 240), radius(70)
Drawing an ellipse: Center(320, 240), x-axis(100), y-axis(70)
Drawing a rectangle: Upper left corner coordinates(320, 240), width(100), height(70)
【提示】
需要自定义Point类。
给定如下main函数:
int main() {
Point p(320, 240);
Mix mix(p, 100, 70);
mix.draw();
return 0;
}
【来源】
《程序设计基础——以C++为例》第7章实验5。(10分)
我的答案:
class Point {
private:
int x, y;
public:
Point(int x1, int x2) {
x = x1;
y = x2;
}
void show() {
cout << “(” << x << ", " << y << “)”;
}
};

class Arc{
private:
Point p;
double radius;
public:
Arc(Point n, double r):p(n){
radius = r;
}
void draw() {
cout << “Drawing an arc: Center”;
p.show();
cout << “, radius(” << radius << “)” << endl;
}
Arc getArc(){
Arc b(p,radius);
return b;
}
};
class Circle {
private:
Point p;
double radius;
public:
Circle(Point n, double r):p(n) {
radius = r;
}
void draw() {
cout << “Drawing an circle: Center”;
p.show();
cout << “, radius(” << radius << “)” << endl;
}
Circle getCircle(){
Circle b(p,radius);
return b;
}

};
class Ellipse {
private:
Point p;
double xRadius, yRadius;
public:
Ellipse(Point n, double r1, double r2):p(n) {
xRadius = r1;
yRadius = r2;
}
void draw() {
cout << “Drawing an ellipse: Center”;
p.show();
cout << “, x-axis(” << xRadius << “)” << “, y-axis(” << yRadius << “)” << endl;
}
Ellipse getEllipse(){
Ellipse b(p,xRadius, yRadius);
return b;
}
};
class Rectangle {
private:
Point p;
double width, height;
public:
Rectangle(Point n, double r1, double r2):p(n) {
width = r1;
height = r2;
}
void draw() {
cout << “Drawing a rectangle: Upper left corner coordinates”;
p.show();
cout << “, width(” << width << “)” << “, height(” << height << “)” << endl;
}
Rectangle getRectangle(){
Rectangle b(p,width,height);
return b;
}
};

class Mix :public Arc, public Circle, public Ellipse, public Rectangle {
public:
Mix(Point n, double r1, double r2) :Arc(n, r1), Circle(n, r2), Ellipse(n, r1, r2), Rectangle(n, r1, r2) {
}
void draw() {
this->getArc().draw();
this->getCircle().draw();
this->getEllipse().draw();
this->getRectangle().draw();
}
};
题目得分 10
参考答案:
#include
using namespace std;
class Point {
public:
Point(double x = 0, double y = 0) {
this->x = x;
this->y = y;
}
double getX() const {
return x;
}
double getY() const {
return y;
}
private:
double x;
double y;
};
class Arc {
public:
Arc(Point p, double radius):p§, radius(radius) { }
void draw() {
cout << “Drawing an arc: Center(” << p.getX() << ", " << p.getY()
<< “), radius(” << radius << “)” << endl;
}
private:
Point p;
double radius;
};
class Circle {
public:
Circle(Point p, double radius):p§, radius(radius) { }
void draw() {
cout << “Drawing a circle: Center(” << p.getX() << ", " << p.getY()
<< “), radius(” << radius << “)” << endl;
}
private:
Point p;
double radius;
};
class Ellipse {
public:
Ellipse(Point p, double xRadius, double yRadius):p§, xRadius(xRadius), yRadius(yRadius) { }
void draw() {
cout << “Drawing an ellipse: Center(” << p.getX() << ", " << p.getY()
<< “), x-axis(” << xRadius << “), y-axis(” << yRadius << “)” << endl;
}
private:
Point p;
double xRadius;
double yRadius;
};
class Rectangle {
public:
Rectangle(Point p, double width, double height):p§, width(width), height(height) { }
void draw() {
cout << “Drawing a rectangle: Upper left corner coordinates(” << p.getX() << ", " << p.getY()
<< “), Width(” << width << “), Height(” << height << “)” << endl;
}
private:
Point p;
double width;
double height;
};
class Mix:public Arc, public Circle, public Ellipse, public Rectangle {
public:
Mix(Point p, double radius1, double radius2)
:Arc(p, radius1), Circle(p, radius2),
Ellipse(p, radius1, radius2), Rectangle(p, radius1, radius2) { }
void draw() {
Arc::draw();
Circle::draw();
Ellipse::draw();
Rectangle::draw();
}
};
int main() {
Point p(320, 240);
Mix mix(p, 100, 70);
mix.draw();
return 0;
}
【描述】
①Employee类是抽象类。Employee类的派生类有Boss类、CommissionWorker类、PieceWorker类和HourlyWorker类。
②Employee类包括私有数据成员name(姓名,string类型);有参构造函数,将name设置为给定的参数;访问器函数getName;还有纯虚函数show和earnings。show和earning函数将在每个派生类中实现,因为每个派生类显示的信息不同、计算工资的方法不同。
③Boss类有固定的周工资且不计工作时间。Boss类包括私有数据成员weeklySalary(周工资,double类型);有参构造函数,将name、weeklySalary设置为给定的参数;更改器函数setWeeklySalary;show函数和earnings函数。
④CommissionWorker类有工资加上销售提成。CommissionWorker类包括私有数据成员salary(工资,double类型)、commission(佣金,double类型)和quantity(销售数量,int类型);有参构造函数,将name、salary、commission、quantity设置为给定的参数;更改器函数setSalary、setCommission和setQuantity;show函数和earnings函数。
⑤PieceWorker类的工资根据其生产的产品数量而定。PieceWorker类包括私有数据成员wagePerPiece(每件产品工资,double类型)、quantity(生产数量,int类型);有参构造函数,将name、wagePerPiece、quantity设置为给定的参数;更改器函数setWage、setQuantity;show函数和earnings函数。
⑥HourlyWorker类的工资根据小时计算并有加班工资。HourlyWorker类包括私有数据成员wage(小时工资,double类型)、hours(工作时数,double类型);有参构造函数,将name、wage、hours设置为给定的参数;更改器函数setWage、setHours;show函数和earnings函数。
动态绑定show和earnings函数显示和计算各类人员的信息和工资。
【输入】
输入Boss的姓名和周工资。
输入CommissonWorker的姓名、工资、佣金和销售数量。
输入PieceWorker的姓名、每件产品工资和生产数量。
输入HourlyWorker的姓名、小时工资、工作时数。
【输出】
见【输出示例】
【输入示例】
ZhangSan 800.0
LiSi 400.0 3.0 150
WangWu 2.5 200
LiuLiu 13.75 40
【输出示例】
Boss: ZhangSan
Earned: $800
Commission Worker: LiSi
Earned: $850
Piece Worker: WangWu
Earned: $500
Hourly Worker: LiuLiu
Earned: $550
【来源】
《程序设计基础——以C++为例》第7章实验7。

(10分)
我的答案:
class Employee{
private:
string name;
public:
Employee(string n){
name=n;
}
string getName(){
return name;
}
virtual int earnings()=0;
virtual void show()=0;
};
class Boss:public Employee{
private:
double weeklySalary;
public:
Boss(string n,double s):Employee(n){
weeklySalary=s;
}
void show(){
cout<<“Boss:”<getName()<<endl;
}
int earnings(){
return (int)weeklySalary;
}
};
class CommissionWorker: public Employee{
private:
double salary;
double commission;
int quantity;
public:
CommissionWorker(string n,double s,double c,int q):Employee(n){
salary = s;
commission = c;
quantity = q;
}
int earnings(){
return (int)salary+commission*quantity;
}
void show(){
cout<<"Commission Worker: "<getName()<<endl;
}

};
class PieceWorker:public Employee{
private:
double wagePerPiece;
int quantity;
public:
PieceWorker(string n,double w,int q):Employee(n){
wagePerPiece=w;
quantity=q;
}
void show(){
cout<<“Piece Worker:”<getName()<<endl;
}
int earnings(){
return (int)(wagePerPiecequantity);
}
};
class HourlyWorker: public Employee{
private:
double wage;
double hours;
public:
HourlyWorker(string n,double w,double h):Employee(n){
wage = w;
hours = h;
}
int earnings(){
return (int)(wage
hours);
}
void show(){
cout<<"Hourly Worker: "<getName()<<endl;
}
};
题目得分 10
参考答案:
#include
#include
using namespace std;
class Employee {
public:
Employee(string name) {
this->name = name;
}
string getName() {
return name;
}
virtual void show() = 0;
virtual double earnings() = 0;
private:
string name;
};
class Boss:public Employee {
public:
Boss(string name, double weeklySalary):Employee(name) {
this->weeklySalary = weeklySalary;
}
void setWeeklySalary(double weeklySalary) {
this->weeklySalary = weeklySalary;
}
void show() {
cout << "Boss: " << getName() << endl;
}
double earnings() {
return weeklySalary;
}
private:
double weeklySalary; // 周工资
};
class CommissionWorker:public Employee {
public:
CommissionWorker(string name, double salary, double commission, int quantity):Employee(name) {
this->salary = salary;
this->commission = commission;
this->quantity = quantity;
}
void setSalary(double salary) {
this->salary = salary;
}
void setCommission(double commission) {
this->commission = commission;
}
void setQuantity(int quantity) {
this->quantity = quantity;
}
void show() {
cout << "Commission Worker: " << getName() << endl;
}
double earnings() {
return salary + commission * quantity; // 工资+销售提成
}
private:
double salary; // 工资
double commission; // 佣金
int quantity; // 销售数量
};
class PieceWorker:public Employee {
public:
PieceWorker(string name, double wagePerPiece, int quantity):Employee(name) {
this->wagePerPiece = wagePerPiece;
this->quantity = quantity;
}
void setWagePerPiece(double wagePerPiece) {
this->wagePerPiece = wagePerPiece;
}
void setQuantity(int quantity) {
this->quantity = quantity;
}
void show() {
cout << "Piece Worker: " << getName() << endl;
}
double earnings() {
return wagePerPiece * quantity;
}
private:
double wagePerPiece; // 每件产品工资
int quantity; // 生产数量
};
class HourlyWorker:public Employee {
public:
HourlyWorker(string name, double wage, double hours):Employee(name) {
this->wage = wage;
this->hours = hours;
}
void setWage(double wage) {
this->wage = wage;
}
void setHours(double hours) {
this->hours = hours;
}
void show() {
cout << "Hourly Worker: " << getName() << endl;
}
double earnings() {
return wage * hours;
}
private:
double wage; // 小时工资
double hours; // 工作时数
};
int main() {
string name;
double weeklySalary, salary, commission, quantity, wagePerPiece, wage, hours;
cin >> name >> weeklySalary;
Boss b(name, weeklySalary);
cin >> name >> salary >> commission >> quantity;
CommissionWorker c(name, salary, commission, quantity);
cin >> name >> wagePerPiece >> quantity;
PieceWorker p(name, wagePerPiece, quantity);
cin >> name >> wage >> hours;
HourlyWorker h(name, wage, hours);
Employee *ref; // 基类指针
ref = &b;
ref->show();
cout << “Earned: $” << ref->earnings() << endl;
ref = &c;
ref->show();
cout << “Earned: $” << ref->earnings() << endl;
ref = &p;
ref->show();
cout << “Earned: $” << ref->earnings() << endl;
ref = &h;
ref->show();
cout << “Earned: $” << ref->earnings() << endl;
return 0;
}
【描述】
有5个类A、B、C、D、E。它们的形式均为:
class T {
public:
T() {
cout << “T()” << endl;
}
~T() {
cout << “~T()” << endl;
}
};
这里T代表类名A、B、C、D、E。
给定如下main函数:
int main() {
E e;
return 0;
}
要求根据输出结果,声明并实现类A、B、C、D、E,确定类A、B、C、D、E之间的继承关系。
【输入】
没有输入。
【输出】
C()
B()
C()
A()
D()
E()
~E()
~D()
~A()
~C()
~B()
~C()

(10分)
我的答案:
class C {
public:
C() {
cout << “C()” << endl;
}
~C() {
cout << “~C()” << endl;
}
};
class B:public C {
public:
B() {
cout << “B()” << endl;
}
~B() {
cout << “~B()” << endl;
}
};
class A :public C {
public:
A() {
cout << “A()” << endl;
}
~A() {
cout << “~A()” << endl;
}
};
class D :public B,public A {
public:
D() {
cout << “D()” << endl;
}
~D() {
cout << “~D()” << endl;
}
};

class E :public D {
public:
E() {
cout << “E()” << endl;
}
~E() {
cout << “~E()” << endl;
}
};
题目得分 10
参考答案:
#include
using namespace std;
class C {
public:
C() {
cout << “C()” << endl;
}
~C(){
cout << “~C()” << endl;
}
};
class A : public C {
public:
A() {
cout << “A()” << endl;
}
~A(){
cout << “~A()” << endl;
}
};
class B : public C {
public:
B() {
cout << “B()” << endl;
}
~B(){
cout << “~B()” << endl;
}
};
class D : public B, public A {
public:
D() {
cout << “D()” << endl;
}
~D(){
cout << “~D()” << endl;
}
};
class E : public D {
public:
E() {
cout << “E()” << endl;
}
~E() {
cout << “~E()” << endl;
}
};
int main() {
E e;
return 0;
}
【描述】
将输入数据按特定要求原样输出。
【输入】
第一行是整数t,表明一共t组数据。
对每组数据:
第一行是整数n,表示下面一共有n行,0<n<100。
下面的每行,以一个字母开头,然后跟着一个整数,两者用空格分隔。字母只会是’A’或’B’。整数范围0到100。
【输出】
对每组输入数据,将其原样输出,每组数据的最后输出一行"****"。
【输入示例】
2
4
A 3
B 4
A 5
B 6
3
A 4
A 3
A 2
【输出示例】
4
A 3
B 4
A 5
B 6


3
A 4
A 3
A 2
****(10分)
我的答案:
class A {
private:
int n;
public:
A(int n) {
this->n=n;
}
void print() {
cout<<"A "<<n<<endl;
}
};
class B : public A {
private:
int m;
public:
B(int n):A(n){
this->m=n;
}
void print() {
cout<<"B “<<m<<endl;
}
};
void PrintInfo(A a){
a->print();
}
A a[100];
题目得分 10
参考答案:
#include
using namespace std;
// 此处填写自己的代码
class A {
protected:
int x;
public:
virtual void Print() {
cout << "A " << x << endl;
}
A(int i):x(i) { }
};
class B:public A {
public:
virtual void Print() {
cout << "B " << x << endl;
}
B(int i):A(i) { }
};
void PrintInfo(A p) {
p->Print();
}
A a[100];
// 填写代码结束
int main() {
int t;
cin >> t;
while(t–) {
int n;
cin >> n;
for(int i = 0; i < n; ++i) {
char c;
int k;
cin >> c >> k;
if(c == ‘A’)
a[i] = new A(k);
else
a[i] = new B(k);
}
cout << n << endl;
for(int i = 0; i < n; ++i)
PrintInfo(a[i]);
cout << "
” << endl;
}
}
【描述】
①声明并实现一个名为Vehicle的基类,表示汽车。Vehicle类包括:
int类型的私有数据成员numberOfDoors,表示车门数量。
int类型的私有数据成员numberOfCylinders,表示气缸数量。
string类型的私有数据成员color,表示汽车颜色。
double类型的私有数据成员fuelLevel,表示油位,即燃油数量。
int类型的私有数据成员transmissionType,表示变速箱类型,即0表示手动、1表示自动。
string类型的私有数据成员className,表示汽车类别。
有参构造函数,将车门数量、气缸数量、汽车颜色、燃油数量、变速箱类型设置为给定的参数。
访问器函数getNumberOfDoors、getNumberOfCylinders、getColor、getFuelLevel、getTransmissionType、getClassNme,分别用于访问车门数量、气缸数量、汽车颜色、燃油数量、变速箱类型、汽车类别。
更改器函数setColor、setFuelLevel、setClassNme,分别用于更改汽车颜色、燃油数量、汽车类别。
重载流插入运算符<<,输出相关信息。
②从Vehicle类派生出Taxi类,表示出租车。Taxi类有数据成员customers(是否载客,bool类型)以及有参构造函数,将车门数量、气缸数量、汽车颜色、燃油数量、变速箱类型、是否载客设置为给定的参数;访问器/更改器函数hasCustomers和setCustomers;重载流插入运算符<<,输出相关信息。
③从Vehicle类派生出Truck类,表示卡车。Truck类有数据成员cargo(是否载货,bool类型)以及有参构造函数,将车门数量、气缸数量、汽车颜色、燃油数量、变速箱类型、是否载货设置为给定的参数;访问器/更改器函数hasCargo和setCargo;重载流插入运算符<<,输出相关信息。
【输入】
输入车门数量、气缸数量,颜色、燃油数量、变速箱类型。
【输出】
见【输出示例】

【输入示例】
2 6 red 50 1
4 6 yellow 60 0
2 16 black 100 0

【输出示例】
Vehicle
Number of doors:2
Number of cylinders:6
Transmission type:Automatic
Color:red
Fuel level:50
Taxi
Number of doors:4
Number of cylinders:6
Transmission type:Manual
Color:yellow
Fuel level:60
Has no passengers
Truck
Number of doors:2
Number of cylinders:16
Transmission type:Manual
Color:black
Fuel level:100
Is carrying cargo

【来源】
《程序设计基础——以C++为例》第7章实验3。(10分)
我的答案:
class Vehicle {
public:
Vehicle(int a, int b,string c,double d, int f){
numberOfDoors=a;
numberOfCylinders=b;
transmissionType=f;
color=c;
fuelLevel=d;
}
Vehicle(const Vehicle &);
int getNumberOfDoors(){
return numberOfDoors;
}
int getNumberOfCylinders(){
return numberOfCylinders;
}
int getTransmissionType(){
return transmissionType;
}
string getColor(){
return color;
}
string getClassNme(){
return className;
}
double getFuelLevel(){
return fuelLevel;
}
void setColor(string a){
color = a;
}
void setFuelLevel(double a){
fuelLevel = a;
}
void setClassNme(string a){
className = a;
}

friend ostream& operator<<(ostream& stream, const Vehicle& x)
{
	stream<<"Vehicle\n"<<"Number of doors:"<<x.numberOfDoors<<endl;
	stream<<"Number of cylinders:"<<x.numberOfCylinders<<endl;
	if(x.transmissionType==1)
	stream<<"Transmission type:Automatic"<<endl;
	else
	stream<<"Transmission type:Manual"<<endl;
	stream<<"Color:"<<x.color<<endl;
	stream<<"Fuel level:"<<x.fuelLevel<<endl;
}

private:
int numberOfDoors, numberOfCylinders,transmissionType;
string color,className;
double fuelLevel;
};
Vehicle::Vehicle(const Vehicle &v){
numberOfDoors = v.numberOfDoors;
numberOfCylinders = v.numberOfCylinders;
transmissionType = v.transmissionType;
color = v.color;
className = v.className;
fuelLevel = v.fuelLevel;
}
class Taxi: public Vehicle{
private:
bool customers;
public:
Taxi(int a, int b,string c,double d, int f, bool e):Vehicle(a,b,c,d,f){
customers = e;
}
bool hasCustomers(){
return customers;
}
friend ostream& operator<<(ostream& stream, const Taxi& y)
{
Taxi x=y;
stream<<“Taxi\n”<<“Number of doors:”<<x.getNumberOfDoors()<<endl;
stream<<“Number of cylinders:”<<x.getNumberOfCylinders()<<endl;
if(x.getTransmissionType()1)
stream<<“Transmission type:Automatic”<<endl;
else
stream<<“Transmission type:Manual”<<endl;
stream<<“Color:”<<x.getColor()<<endl;
stream<<“Fuel level:”<<x.getFuelLevel()<<endl;
if(x.customers
0)
stream<<“Has no passengers”<<endl;
else
stream<<“Has passengers”<<endl;
}
};
class Truck: public Vehicle{
private:
bool cargo;
public:
Truck(int a, int b,string c,double d, int f, bool e):Vehicle(a,b,c,d,f){
cargo = e;
}
bool hasCargo(){
return cargo;
}
friend ostream& operator<<(ostream& stream, const Truck& y)
{
Truck x = y;
stream<<“Truck\n”<<“Number of doors:”<<x.getNumberOfDoors()<<endl;
stream<<“Number of cylinders:”<<x.getNumberOfCylinders()<<endl;
if(x.getTransmissionType()1)
stream<<“Transmission type:Automatic”<<endl;
else
stream<<“Transmission type:Manual”<<endl;
stream<<“Color:”<<x.getColor()<<endl;
stream<<“Fuel level:”<<x.getFuelLevel()<<endl;
if(x.cargo
1)
stream<<“Is carrying cargo”<<endl;
else
stream<<“Isn’t’ carrying cargo”<<endl;
}
};
题目得分 10
参考答案:
#include
#include
using namespace std;
class Vehicle {
public:
Vehicle(int doors, int cylinders, string color, double fuel, int transmission);
int getNumberOfDoors() const;
int getNumberOfCylinders() const;
string getColor() const;
double getFuelLevel() const;
int getTransmissionType() const;
string getClassName() const;
void setColor(string color);
void setFuelLevel(double fuel);
void setClassName(string className);
private:
int numberOfDoors; // 车门数量
int numberOfCylinders;// 气缸数量
string color; // 汽车颜色
double fuelLevel; // 油位
int transmissionType; // 变速箱类型
string className; // 汽车类别
friend ostream &operator<<(ostream &out, const Vehicle &v);
};
Vehicle::Vehicle(int doors, int cylinders, string color, double fuel, int transmission) {
numberOfDoors = doors;
numberOfCylinders = cylinders;
this->color = color;
fuelLevel = fuel;
transmissionType = transmission;
className = “Vehicle”;
}
int Vehicle::getNumberOfDoors() const {
return numberOfDoors;
}
int Vehicle::getNumberOfCylinders() const {
return numberOfCylinders;
}
string Vehicle::getColor() const {
return color;
}
double Vehicle::getFuelLevel() const {
return fuelLevel;
}
int Vehicle::getTransmissionType() const {
return transmissionType;
}
string Vehicle::getClassName() const {
return className;
}
void Vehicle::setColor(string color) {
this->color = color;
}
void Vehicle::setFuelLevel(double fuel) {
fuelLevel = fuel;
}
void Vehicle::setClassName(string className) {
this->className = className;
}
ostream &operator<<(ostream &out, const Vehicle &v) {
string msg;
out << v.className << endl
<< “Number of doors:” << v.numberOfDoors << endl
<< “Number of cylinders:” << v.numberOfCylinders << endl;
if(v.transmissionType == 0)
msg = “Manual”;
else
msg = “Automatic”;
out << “Transmission type:” << msg << endl
<< “Color:” << v.color << endl
<< “Fuel level:” << v.fuelLevel << endl;
return out;
}
class Taxi:public Vehicle {
public:
Taxi(int doors, int cylinders, string color, double fuel, int transmission, bool customers);
void setCustomers(bool customers);
bool hasCustomers() const;
private:
bool customers;
friend ostream &operator<<(ostream &out, const Taxi &t);
};
Taxi::Taxi(int doors, int cylinders, string color, double fuel, int transmission, bool customers)
:Vehicle(doors, cylinders, color, fuel, transmission) {
this->customers = customers;
setClassName(“Taxi”);
}
void Taxi::setCustomers(bool customers) {
this->customers = customers;
}
bool Taxi::hasCustomers() const {
return customers;
}
ostream &operator<<(ostream &out, const Taxi &t) {
string msg;
out << t.getClassName()<< endl
<< “Number of doors:” << t.getNumberOfDoors() << endl
<< “Number of cylinders:” << t.getNumberOfCylinders() << endl;
if(t.getTransmissionType() == 0)
msg = “Manual”;
else
msg = “Automatic”;
out << “Transmission type:” << msg << endl
<< “Color:” << t.getColor() << endl
<< “Fuel level:” << t.getFuelLevel() << endl;
if(t.hasCustomers())
msg = “Has passengers”;
else
msg = “Has no passengers”;
out << msg << endl;
return out;
}
class Truck:public Vehicle {
public:
Truck(int doors, int cylinders, string color, double fuel, int transmission, bool cargo);
void setCargo(bool cargo);
bool hasCargo() const;
private:
bool cargo;
friend ostream &operator<<(ostream &out, const Truck &t);
};
Truck::Truck(int doors, int cylinders, string color, double fuel, int transmission, bool cargo)
:Vehicle(doors, cylinders, color, fuel, transmission) {
this->cargo = cargo;
setClassName(“Truck”);
}
void Truck::setCargo(bool cargo) {
this->cargo = cargo;
}
bool Truck::hasCargo() const {
return cargo;
}
ostream &operator<<(ostream &out, const Truck &t) {
string msg;
out << t.getClassName()<< endl
<< “Number of doors:” << t.getNumberOfDoors() << endl
<< “Number of cylinders:” << t.getNumberOfCylinders() << endl;
if(t.getTransmissionType() == 0)
msg = “Manual”;
else
msg = “Automatic”;
out << “Transmission type:” << msg << endl
<< “Color:” << t.getColor() << endl
<< “Fuel level:” << t.getFuelLevel() << endl;
if(t.hasCargo())
msg = “Is carrying cargo”;
else
msg = “Is not carrying cargo”;
out << msg << endl;
return out;
}
int main() {
int doors, cylinders, transmission;
string color;
double fuel;
cin >> doors >> cylinders >> color >> fuel >> transmission;
Vehicle vehicle(doors, cylinders, color, fuel, transmission);
cout << vehicle;
cin >> doors >> cylinders >> color >> fuel >> transmission;
Taxi taxi(doors, cylinders, color, fuel, transmission, false);
cout << taxi;
cin >> doors >> cylinders >> color >> fuel >> transmission;
Truck truck(doors, cylinders, color, fuel, transmission, true);
cout << truck;
return 0;
}
【描述】
下面是不完整的类定义:
class A {
public:
virtual void print(){
cout << “print come form class A” << endl;
}
};
class B : public A {
private:
char *buf;
public:
void print() {
cout << “print come from class B” << endl;
}
};
void fun(A *a) {
delete a;
}
试完成其定义(需要增加必要的构造函数、析构函数)。
类A析构函数输出:A::~A() called

类B析构函数输出:B::~B() called

给定如下main函数:
int main() {
A *a = new B(10);
a->print();
fun(a);
B *b = new B(20);
fun(b);
return 0;
}
【输入】
没有输入。
【输出】
主函数的输出已经写好。(10分)
我的答案:
class A {
public:
A(int x){
}
virtual void print(){
cout << “print come form class A” << endl;
}
virtual ~A(){
cout<<“A::~A() called”<<endl;
}
};
class B : public A {
private:
char *buf;
public:
B(int n):A(n) {
}
void print() {
cout << “print come from class B” << endl;
}
~B(){
cout<<“B::~B() called”<<endl;
}
};
题目得分 10
参考答案:
#include
using namespace std;
class A {
public:
virtual ~A() {
cout << “A::~A() called” << endl;
}
virtual void print(){
cout << “print come form class A” << endl;
}
};
class B : public A {
private:
char *buf;
public:
B(int size) {
buf = new char[size];
}
~B() {
delete buf;
cout << “B::~B() called” << endl;
}
void print() {
cout << “print come from class B” << endl;
}
};
void fun(A *a) {
delete a;
}
int main() {
A *a = new B(10);//调用A的无参(默认)构造函数
a->print();
fun(a);
B *b = new B(20);
fun(b);
return 0;
}
【描述】
按要求计算数值。
【输入】
第一行是整数n,表示第二行有n个整数。
第二行:n个整数。
所有整数都在0和100之间。
【输出】
先输出:
1
100
101
101
对于输入中第二行的每个整数x,输出两行:
第一行:k=x;
第二行:x的平方。
【输入示例】
3
3 4 5
【输出示例】
1
100
101
101
k=3
9
k=4
16
k=5
25

(10分)
我的答案:
A(int x){
n=x;
}
int getx(){
return n;
}
A& operator++(){
n++;
return *this;
}

const A operator++(int){
	A obj(*this);
	++(*this);
	return obj;
}
friend ostream& operator<<(ostream& stream, const A& x){
	A obj(x.n);
stream<<obj.n;
return stream;
}
operator int()
{
    return n;
}

题目得分 10
参考答案:
#include
#include
using namespace std;
class A {
private:
int n;
public:
//此处填写自己的代码
A(int i):n(i) { }
operator int() {
return n;
}
A &operator++() {
++n;
return *this;
}
A operator++(int) {
A tmp(*this);
++n;
return tmp;
}
// 填写代码结束
};
class B {
private:
static int k;
static int Square(int n) {
cout << “k=” << k <<endl;
return n * n;
}
friend int main();
};
int B::k;
int main() {
A a1(1), a2(2);
cout << a1++ << endl;
(++a1) = 100;
cout << a1 << endl;
cout << ++a1 << endl;
cout << a1 << endl;
int n;
cin >> n;
while(n --) {
cin >> B::k;
A a3(B::k);
cout << B::Square(a3) << endl;
}
return 0;
}
【描述】
①声明并实现一个名为Person的基类,Person类有保护数据成员name(姓名,string类型)、sex(性别,char类型,'M’表示男,'F’表示女)。以及有参构造函数,将姓名、性别设置为给定的参数;成员函数print,输出姓名和性别。
②从Person类派生出Student类,Student类有私有数据成员status(状态,枚举类型),表示年级(FRESHMAN、SOPHOMORE、JUNIOR、SENIOR),表示大一、大二、大三、大四学生。以及有参构造函数,将姓名、性别、状态设置为给定的参数;成员函数print,print函数输出姓名、性别和状态。
③定义MyDate类,它包含私有数据成员year、month和day以及带默认参数的有参构造函数,年、月、日的默认参数值分别为1900、1、1;成员函数print,输出年、月、日。
④从Person类派生出Employee类,Employee类有保护数据成员salary(薪水,int类型)、dateHired(雇佣日期),dataHired的类型是MyDate。以及有参构造函数,将姓名、性别、薪水和雇佣日期设置为给定的参数;成员函数print,输出姓名、性别、薪水和雇佣日期。
⑤从Employee类派生出Faculty类,Faculty类有私有数据成员rank(级别,枚举类型),有(PROFESSOR、ASSOCIATE_PROFESSOR、LECTURER),表示教授、副教授、讲师。以及有参构造函数,将姓名、性别、薪水、雇佣日期和级别设置为给定的参数;成员函数print,输出姓名、性别、薪水、雇佣日期和级别。
⑥从Employee类派生出Staff类,Staff类有私有数据成员headship(职务,枚举类型),有(PRESIDENT、DEAN、DEPARTMENT_CHAIRMAN),表示校长、院长、系主任。以及有参构造函数,将姓名、性别、薪水、雇佣日期和职务设置为给定的参数;成员函数print,输出姓名、性别、薪水、雇佣日期和职务。
【输入】
没有输入。
【输出】
Name:ZhangSan, Sex:M
Name:LiSi, Sex:F
Status:Freshman
Name:WangWu, Sex:M
Salary:5000, Hire date:2012-3-1
Name:LiuLiu, Sex:M
Salary:10000, Hire date:2012-3-1
Rank:Professor
Name:QianQi, Sex:M
Salary:8000, Hire date:2012-3-1
Headship:Department chairman
【来源】
《程序设计基础——以C++为例》第7章实验4。

(10分)
我的答案:
enum headship { PRESIDENT, DEAN, DEPARTMENT_CHAIRMAN };
enum status { FRESHMAN, SOPHOMORE, JUNIOR, SENIOR };
enum ranks { PROFESSOR, ASSOCIATE_PROFESSOR, LECTURER };
class Person {
public:
Person(string n, char s) {
name = n;
sex = s;
}
Person(const Person&);
string getName() {
return name;
}
char getSex() {
return sex;
}
void print() {
cout << “Name:” << name << “, Sex:” << sex << endl;
}
private:
string name;
char sex;
};
Person::Person(const Person& v) {
name = v.name;
sex = v.sex;
}
class Student : public Person {
private:
status m;
public:

Student(string n, char s, status st) :Person(n, s) {
	m = st;
}
void print() {
	cout << "Name:" << this->getName() << ", Sex:" << this->getSex() << endl;
	cout<<"Status:";
	switch (m) {
	case 0:cout << "Freshman" << endl; break;
	case 1:cout << "Sophmore" << endl; break;
	case 2:cout << "Junior" << endl; break;
	case 3:cout << "Senior" << endl;
	}
}

};
class MyDate {
private:
int year, month, day;
public:
MyDate(const MyDate& x) {
year = x.year;
month = x.month;
day = x.day;
}
MyDate(int y = 1900, int m = 1, int d = 1) {
year = y;
month = m;
day = d;
}
void print() {
cout << year << “-” << month << “-” << day << endl;
}
};
class Employee :public Person {
private:
int salary;
MyDate dateHired;
public:
Employee(string n, char s, int sa, MyDate date) :Person(n, s) {
salary = sa;
dateHired = date;

}
int getSalary() {
	return salary;
}
MyDate getDateHired() {
	return dateHired;
}
void print() {
	cout << "Name:" << this->getName() << ", Sex:" << this->getSex() << endl;
	cout << "Salary:" << salary << ", Hire date:";
	dateHired.print();
}

};
class Faculty :public Employee {
private:
ranks n;
public:
Faculty(string n, char s, int sa, MyDate date, ranks ra) :Employee(n, s, sa, date) {
n = ra;
}
void print() {
cout << “Name:” << this->getName() << “, Sex:” << this->getSex() << endl;
cout << “Salary:” << this->getSalary() << “, Hire date:”;
this->getDateHired().print();

	cout<<"Rank:";
	switch (n) {
	case 0:cout << "Proessor" << endl; break;
	case 1:cout << "Associate professor" << endl; break;
	case 2:cout << "Lecturer" << endl;
	}
}

};

class Staff :public Employee {
private:
headship z;
public:
Staff(string n, char s, int sa, MyDate date, headship ra) :Employee(n, s, sa, date) {
z = ra;
}
void print() {
cout << “Name:” << this->getName() << “, Sex:” << this->getSex() << endl;
cout << “Salary:” << this->getSalary() << “, Hire date:”;
this->getDateHired().print();

	cout<<"Headship:";
	switch (z) {
	case 0:cout << "President" << endl; break;
	case 1:cout << "Dean" << endl; break;
	case 2:cout << "Department chairman" << endl;
	}
}

};
题目得分 10
参考答案:
#include
#include
using namespace std;
class Person {
public:
Person(string name, char sex) {
this->name = name;
this->sex = sex;
}
void print() {
cout << “Name:” << name << “, Sex:” << sex << endl;
}
protected:
string name;
char sex;
};
enum Status {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};
class Student:public Person {
public:
Student(string name, char sex, Status status):Person(name, sex) {
this->status = status;
}
void print() {
string msg;
Person::print();
switch(status) {
case FRESHMAN:
msg = “Freshman”;
break;
case SOPHOMORE:
msg = “Sophomore”;
break;
case JUNIOR:
msg = “Junior”;
break;
case SENIOR:
msg = “Senior”;
break;
}
cout << “Status:” << msg << endl;
}
private:
Status status;
};
class MyDate {
public:
MyDate(int year = 1900, int month = 1, int day = 1) {
this->year = year;
this->month = month;
this->day = day;
}
void print() {
cout << year << “-” << month << “-” << day << endl;
}
private:
int year;
int month;
int day;
};
class Employee:public Person {
public:
Employee(string name, char sex, int salary, MyDate &dateHired)
:Person(name, sex) {
this->salary = salary;
this->dateHired = dateHired;
}
void print() {
Person::print();
cout << “Salary:” << salary << “, Hire date:”;
dateHired.print();
}
protected:
int salary;
MyDate dateHired;
};
enum Rank {PROFESSOR, ASSOCIATE_PROFESSOR, LECTURER};
class Faculty:public Employee {
public:
Faculty(string name, char sex, int salary, MyDate &dateHired, Rank rank)
:Employee(name, sex, salary, dateHired) {
this->rank = rank;
}
void print() {
string msg;
Employee::print();
switch(rank) {
case PROFESSOR:
msg = “Professor”;
break;
case ASSOCIATE_PROFESSOR:
msg = “Associate professor”;
break;
case LECTURER:
msg = “Lecturer”;
break;
}
cout << “Rank:” << msg << endl;
}
private:
Rank rank;
};
enum Headship {PRESIDENT, DEAN, DEPARTMENT_CHAIRMAN};
class Staff:public Employee {
public:
Staff(string name, char sex, int salary, MyDate &dateHired, Headship headship)
:Employee(name, sex, salary, dateHired) {
this->headship = headship;
}
void print() {
string msg;
Employee::print();
switch(headship) {
case PRESIDENT:
msg = “President”;
break;
case DEAN:
msg = “Dean”;
break;
case DEPARTMENT_CHAIRMAN:
msg = “Department chairman”;
break;
}
cout << “Headship:” << msg << endl;
}
private:
Headship headship;
};
int main() {
Person person(“ZhangSan”, ‘M’);
Student student(“LiSi”, ‘F’, FRESHMAN);
MyDate date(2012, 3, 1);
Employee employee(“WangWu”, ‘M’, 5000, date);
Faculty faculty(“LiuLiu”, ‘M’, 10000, date, PROFESSOR);
Staff staff(“QianQi”, ‘M’, 8000, date, DEPARTMENT_CHAIRMAN);
person.print();
student.print();
employee.print();
faculty.print();
staff.print();
return 0;
}
【描述】
下面是类A的定义,需要补充或增加完整的无参构造函数、虚析构函数以及fun()虚函数。
class A {
public:
// …
void g() {
fun();
}
};
构造函数输出:A constructor,并调用g()函数
析构函数输出:A destructor
fun()函数输出:Call class A’s fun
下面是类B的定义,继承类A,需要补充或增加完整的无参构造函数、析构函数。
class B {
public:
// …
};
无参构造函数输出:B constructor
析构函数输出:B destructor
下面是类C的定义,继承类B,需要补充或增加完整的无参构造函数、析构函数以及fun()函数。
class C {
public:
// …
};
无参构造函数输出:C constructor
析构函数输出:C destructor
fun()函数输出:Call class C’s fun
给定如下main函数:
int main() {
A *a = new C;
a->g();
delete a;
return 0;
}
【输入】
没有输入。
【输出】
主函数的输出已经写好。
(10分)
我的答案:
class A{
public:
A(){
cout<<“A constructor”<<endl;
g();
}
virtual ~A(){
cout<<“A destructor”<<endl;
}
virtual void fun(){
cout<<“Call class A’s fun”<<endl;
}
void g(){
fun();
}
};
class B:public A{
public:
B(){
cout<<“B constructor”<<endl;
}
~B(){
cout<<“B destructor”<<endl;
}
};
class C:public B{
public:
C(){
cout<<“C constructor”<<endl;
}
~C(){
cout<<“C destructor”<<endl;
}
void fun(){
cout<<“Call class C’s fun”<<endl;
}
};
题目得分 10
参考答案:
#include
using namespace std;
class A {
public:
A() {
cout << “A constructor” << endl;
g();
}
virtual ~A() {
cout << “A destructor” << endl;
}
void g() {
fun();
}
virtual void fun() {
cout << “Call class A’s fun” << endl;
}
};
class B : public A {
public:
B() {
cout << “B constructor” << endl;
}
~B() {
cout << “B destructor” << endl;
}
};
class C : public B {
public:
C() {
cout << “C constructor” << endl;
}
~C() {
cout << “C destructor” << endl;
}
void fun() {
cout << “Call class C’s fun” << endl;
}
};
int main() {
A *a = new C;
a->g();
delete a;
return 0;
}
【描述】
①Shape类是抽象类,包括了纯虚函数getArea(求面积)、getPerimeter(求周长)、show(输出对象信息)以及成员函数getClassName(返回类名“Shape”)。
②Circle类继承了Shape类,包括了double类型的私有数据成员radius,表示圆半径;带默认参数的有参构造函数,radius的默认参数值为1;访问器函数getRadius和更改器函数setRadius;重定义了getArea(求圆面积)、getPerimeter(求圆周长)、show(输出半径)、getClassName(返回类名“Circle”)函数。
③Rectangle继承了Shape类,包括了double类型的私有数据成员width、height,分别表示矩形的宽度和高度;带默认参数的有参构造函数,width和height的默认参数值分别为1、1;访问器函数getWidth、getHeight和更改器函数setWidth、setHeight;重定义了getArea(求矩形面积)、getPerimeter(求矩形周长)、show(输出宽度和高度)、getClassName(返回类名“Rectangle”)函数。
④Triangle类继承了Shape类,包括了double类型的私有数据成员side1、side2和side3,表示三角形三条边;有参构造函数,将三角形三条边设置为给定的参数;重定义了getArea(求三角形面积)、getPerimeter(求三角形周长)、show(输出三条边)、getClassName(返回类名“Triangle”)函数。
假设PI为3.14159。
【输入】
输入圆的半径、矩形的宽度和高度以及三角形的三条边。
【输出】
见【输出示例】
【输入示例】
3.5
5.8 11.8
1 1.5 1
【输出示例】

Circle:
Radius:3.5
Area:38.4845, Perimeter:21.9911
Rectangle:
Width:5.8, Height:11.8
Area:68.44, Perimeter:35.2
Triangle:
Side:1, 1.5, 1
Area:0.496078, Perimeter:3.5
【来源】
《程序设计基础——以C++为例》第7章实验6。

(10分)
我的答案:
class Shape{
public:
virtual double getArea()=0;
virtual double getPerimeter()=0;
virtual void show()=0;
virtual string getClassName(){
return “Shape”;
}
};
class Circle:public Shape{
private:
double radius;
public:
Circle(double r=1){
radius=r;
}
double getRadius(){
return radius;
}
double getArea(){
return PIradiusradius;
}
double getPerimeter(){
return PIradius2;
}
void show(){
cout<<“Radius:”<<radius<<endl;
}
string getClassName(){
return “Circle”;
}
};
class Rectangle:public Shape{
private:
double width,height;
public:
Rectangle(double w=1,double h=1){
width=w;
height=h;
}
double getWidth(){
return width;
}
double getHeight(){
return height;
}
double getArea(){
return widthheight;
}
double getPerimeter(){
return 2
(width+height);
}
void show(){
cout<<“Width:”<<width<<",Height:"<<height<<endl;
}
string getClassName(){
return “Rectangle”;
}
};
class Triangle:public Shape{
private:
double side1,side2,side3;
public:
Triangle(double s1,double s2,double s3){
side1=s1;
side2=s2;
side3=s3;
}
double getArea(){
double p=(side1+side2+side3)/2;
return sqrt(p*(p-side1)(p-side2)(p-side3));
}
double getPerimeter(){
return (side1+side2+side3);
}
void show(){
cout<<“Side:”<<side1<<","<<side2<<","<<side3<<endl;
}
string getClassName(){
return “Triangle”;
}
};
题目得分 10
参考答案:
#include
#include
#include
using namespace std;
const double PI = 3.14159;
class Shape {
public:
virtual double getArea() = 0;
virtual double getPerimeter() = 0;
virtual void show() = 0;
string getClassName() {
return “Shape”;
};
};
class Circle : public Shape {
public:
Circle(double radius = 1) {
this->radius = radius;
}
double getRadius() {
return radius;
}
void setRadius(double radius) {
this->radius = radius;
}
double getArea() {
return PI * radius * radius;
}
double getPerimeter() {
return 2 * PI * radius;
}
void show() {
cout << “Radius:” << radius << endl;
}
string getClassName() {
return “Circle”;
}
private:
double radius;
};
class Rectangle : public Shape {
public:
Rectangle(double width = 1, double height = 1) {
this->width = width;
this->height = height;
}
double getWidth() {
return width;
}
double getHeight() {
return height;
}
void setWidth(double width) {
this->width = width;
}
void setHeight(double height) {
this->height = height;
}
double getArea() {
return width * height;
}
double getPerimeter() {
return 2 * (width + height);
}
void show() {
cout << “Width:” << width << “, Height:” << height << endl;
}
string getClassName() {
return “Rectangle”;
}
private:
double width, height;
};
class Triangle : public Shape {
public:
Triangle(double side1, double side2, double side3) {
this->side1 = side1;
this->side2 = side2;
this->side3 = side3;
}
double getArea() {
double s = getPerimeter() / 2;
return sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
double getPerimeter() {
return side1 + side2 + side3;
}
void show() {
cout << “Side:” << side1 << ", " << side2 << ", " << side3 << endl;
}
string getClassName() {
return “Triangle”;
}
private:
double side1, side2, side3;
};
int main() {
double radius, width, height, side1, side2, side3;
cin >> radius;
Circle circle(radius);
cin >> width >> height;
Rectangle rectangle(width, height);
cin >> side1 >> side2 >> side3;
Triangle triangle(side1, side2, side3);
cout << circle.getClassName() << “:” << endl;
circle.show();
cout << “Area:” << circle.getArea();
cout << “, Perimeter:” << circle.getPerimeter() << endl;
cout << rectangle.getClassName() << “:” << endl;
rectangle.show();
cout << “Area:” << rectangle.getArea();
cout << “, Perimeter:” << rectangle.getPerimeter() << endl;
cout << triangle.getClassName() << “:” << endl;
triangle.show();
cout << “Area:” << triangle.getArea();
cout << “, Perimeter:” << triangle.getPerimeter() << endl;
return 0;
}

【描述】
输入10个整数存入文本文件example.txt中,文件每行存放5个整数,每行整数之间用一个空格间隔。行末不能有多余的空格。
【输入】
输入10个整数。
【输出】
生成文件example.txt,里面存放输入的10个整数。
不需要在屏幕上显示整数。
【输入示例】
1 2 3 4 5 6 7 8 9 10
【输出示例】
生成文件example.txt,其中内容:
1 2 3 4
6 7 8 9 10
【来源】
《程序设计基础——以C++为例》第8章实验1。

(10分)
我的答案:
#include
#include
#include
using namespace std;
int main(){
ofstream outFile;
outFile.open(“example.txt”);
if(!outFile.is_open()){
exit(EXIT_FAILURE);
}
int x;
for(int i=0;i<10;++i){
cin>>x;
outFile<<x;
if(i==4)
outFile<<endl;
else
outFile<<" ";
}
outFile.close();
return 0;
}
题目得分 10
参考答案:
#include
#include
#include
using namespace std;
int main() {
ofstream outFile;
outFile.open(“example.txt”);
if(!outFile.is_open()) {
exit(EXIT_FAILURE);
}
int count = 1;
int x;
for(int i = 0; i < 10; ++i) {
cin >> x;
outFile << x;
if(count++ % 5 == 0)
outFile << endl;
else
outFile << " ";
}
outFile.close();
return 0;
}
【描述】
处理日志文件,日志文件的储存格式为“年/月/日 时:分:秒 用户名 操作”。
日志文件有多条记录:
2015/4/218:00:33 37c3b6b58c6ac3 LOGIN
2015/4/218:15:35 11734e186f24fe4c LOGIN
2015/4/218:34:57 9f3cf331d19a9f LOGIN
2015/4/219:00:29 389bcca2159f5de7 LOGIN
2015/4/219:08:29 c3bde693fdb3c3d LOGIN
……
可以下载日志文件:
鼠标右键另存为
【输入】
日志文件log.txt。(该文件已经存在,无需自己创建)
【输出】
生成文件times.txt,里面存放活跃用户的在线时长。
不需要在屏幕上显示信息。
【输入示例】

【输出示例】
文件times.txt,注意:这里只给出了其中部分内容。
37c3b6b58c6ac 31887052
11734e186f24fe4c 2088931
9f3cf331d19a9f 2147511
389bcca2159f5de 71398643
c3bde693fdb3c3d 1297166
……
【提示】
活跃用户指的是在日志文件中有过操作的用户,记得把重复出现的用户去掉。
在线时长单位为秒。为简单起见,日志文件中日期都为同一年的。

(10分)
我的答案:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll daytime = 86400;
FILE* IN;
FILE* OUT;
struct MM {
char use[100];
ll sum;
ll last;
}a[10100];
ll get(char date[], char time[]) {
ll ans = 0;
int month = date[5] - ‘0’;
int day;
if (strlen(date) == 9) {
day = (date[7] - ‘0’) * 10 + date[8] - ‘0’;
}
else
day = date[7] - ‘0’;
if (month == 4) {
ans += (1ll * day - 21) * daytime;
}
else if (month == 5) {
ans += daytime * (1ll * 10 + day - 1);
}
else {
ans += daytime * (1ll * 41 + day - 1);
}
int hour, min, sec;
if (strlen(time) == 7) {
hour = time[0] - ‘0’;
min = (time[2] - ‘0’) * 10 + time[3] - ‘0’;
sec = (time[5] - ‘0’) * 10 + time[6] - ‘0’;
}
else {
hour = (time[0] - ‘0’) * 10 + time[1] - ‘0’;
min = (time[3] - ‘0’) * 10 + time[4] - ‘0’;
sec = (time[6] - ‘0’) * 10 + time[7] - ‘0’;
}
ans += 1ll * hour * 3600 + 1ll * min * 60 + 1ll * sec;
return ans;
}
int pos;
int insert(char name[]) {
for (int i = 1; i <= pos; i++) {
if (strcmp(name, a[i].use) == 0)return i;
}
strcpy(a[++pos].use, name);
a[pos].sum = 0;
a[pos].last = 0;
return pos;
}
int main() {
IN = fopen(“log.txt”, “r”);
OUT = fopen(“times.txt”, “w”);
char date[100], time[100], name[100], op[100];
pos = 0;
while (~fscanf(IN, “%s %s %s %s”, date, time, name, op)) {
int x = insert(name);
int tt = get(date, time);
if (strcmp(op, “LOGIN”) == 0) {
a[x].last = tt;
}
else {
a[x].sum += tt - a[x].last;
}
}
for (int i = 1; i <= pos; i++) {
fprintf(OUT, “%s %d\n”, a[i].use, a[i].sum);
}
return 0;
}
题目得分 10
参考答案:
#include
#include
#include
using namespace std;
/* 时间类型的结构定义 /
struct Time_t {
int year, month, day;
int hour, minute, second;
};
/
计算时长的函数声明 /
int timeDifference(Time_t, Time_t);
int main() {
ifstream fin(“log.txt”);
int user_count = 0; /
用户数,初始值为0 /
string ids[600]; /
记录所有的编号 /
bool online[600]; /
在线状态 /
Time_t last_on[600]; /
上次登录时间 /
int secs[600]; /
累计在线秒数 /
while(!fin.eof()) {
Time_t t;
string id, operation;
char tmp;
fin >> t.year >> tmp >> t.month >> tmp >> t.day;
fin >> t.hour >> tmp >> t.minute >> tmp >> t.second;
fin >> id;
fin >> operation;
/
线性查找 /
int found = -1;
for(int i = 0; i < user_count; ++i)
if(id == ids[i]) {
found = i;
break;
}
/
如果没找到,说明是新用户,记录 /
if(found == -1) {
ids[user_count] = id;
/
记录新用户的登陆状态 /
if(operation == “LOGIN”) {
online[user_count] = true;
last_on[user_count] = t;
}
else
online[user_count] = false;
secs[user_count] = 0;
++user_count;
}
/
否则,修改登录状态,计算登录时长 /
else {
if(operation == “LOGIN”) {
if(!online[found]) {
online[found] = true;
last_on[found] = t;
}
}
else {
if(online[found]) {
online[found] = false;
/
调用函数,计算两个时刻之差 /
secs[found] += timeDifference(last_on[found], t);
}
}
}
}
fin.close();
/
输出每个用户的在线时长 /
ofstream fout(“times.txt”);
for(int i = 0; i < user_count; ++i)
fout << ids[i] << " " << secs[i] << endl;
fout.close();
return 0;
}
/
计算时间差,日期在同一年 */
int timeDifference(Time_t t1, Time_t t2) {
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int day_count = t2.day - t1.day;
for(int i = t1.month; i < t2.month; ++i)
day_count += days[i - 1];
int result = day_count * 60 * 60 * 24;
result += (t2.hour - t1.hour) * 60 * 60;
result += (t2.minute - t1.minute) * 60;
result += (t2.second - t1.second);
return result;
}
【描述】
声明并实现了一个Rectangle类,表示矩形。Rectangle类包括:
double类型的私有数据成员width和height,表示矩形的宽和高。
带默认参数的构造函数,将矩形的宽和高设置为给定的参数。宽和高的默认参数值为1。
更改器函数setWidth和setHeight,分别用于修改矩形的宽和高。
访问器函数getWidth和getHeight,分别用于访问矩形的宽和高。
成员函数computeArea,返回矩形的面积。
成员函数computePerimeter,返回矩形的周长。
创建5个Rectangle对象(每个Rectangle对象的宽和高分别为1、2、3、4、5)并将它们写入二进制文件object.dat中。修改第3个对象的宽为10、高为3.5,再把修改后的该对象写回文件原位置。
【输入】
没有输入。
【输出】
生成文件object.dat
不需要在屏幕上显示信息。
【来源】
《程序设计基础——以C++为例》第8章实验4。(10分)
我的答案:
#include
#include
#include
using namespace std;
class Rectangle{
private:
double width,height;
public:
Rectangle(double w=1,double h=1){
width=w;
height=h;
}
void setWidth(double w){
width=w;
}
void setHeight(double h){
height=h;
}
};
int main(){
fstream ioFile;
ioFile.open(“object.dat”,ios::in|ios::out|ios::trunc|ios::binary);
if(!ioFile.is_open()){
exit(EXIT_FAILURE);
}
Rectangle r1;
Rectangle r2(2,2);
Rectangle r3(3,3);
Rectangle r4(4,4);
Rectangle r5(5,5);
ioFile.write(reinterpret_cast<char *>(&r1),sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r2),sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r3),sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r4),sizeof(Rectangle));
ioFile.write(reinterpret_cast<char >(&r5),sizeof(Rectangle));
r3.setWidth(10);
r3.setHeight(3.5);
ioFile.seekp(2
sizeof(Rectangle),ios::beg);
ioFile.write(reinterpret_cast<char *>(&r3),sizeof(Rectangle));
ioFile.close();
return 0;
}
题目得分 10
参考答案:
#include
#include
#include
using namespace std;
class Rectangle {
public:
Rectangle(double width = 1, double height = 1) {
this->width = width;
this->height = height;
}
void setWidth(double width) {
this->width = width;
}
void setHeight(double height) {
this->height = height;
}
double getWidth() const {
return width;
}
double getHeight() const {
return height;
}
double computeArea() const {
return width * height;
}
double computePerimeter() const {
return 2 * (width + height);
}
private:
double width;
double height;
};
int main() {
fstream ioFile;
ioFile.open(“object.dat”, ios::in | ios::out | ios::trunc | ios::binary);
if(!ioFile.is_open()) {
exit(EXIT_FAILURE);
}
Rectangle r1;
Rectangle r2(2, 2);
Rectangle r3(3, 3);
Rectangle r4(4, 4);
Rectangle r5(5, 5);
ioFile.write(reinterpret_cast<char *>(&r1), sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r2), sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r3), sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r4), sizeof(Rectangle));
ioFile.write(reinterpret_cast<char *>(&r5), sizeof(Rectangle));
Rectangle ra;
ra.setWidth(10);
ra.setHeight(3.5);
ioFile.seekp(2 * sizeof(Rectangle), ios::beg);
ioFile.write(reinterpret_cast<char *>(&ra), sizeof(Rectangle));
ioFile.close();
return 0;
}
【描述】
给定文件hours.txt,其中包含每个员工工作时间的记录。每一行表示一周的工作时间。每周有7天,所以每行最多有7个数字。规定每周从周一开始,文件中的每一行都是从周一的工作小时数开始,后面是周二,等等,周日的数字放在这一行的最后。每行中的数字可以少于7个,因为员工并不是每天都要工作。下面是文件hours.txt的内容:
8 8 8 8 8
8 4 8 4 8 4 4
8 4 8 4 8
3 0 0 8 6 4 4
8 8
0 0 8 8
8 8 4 8 4
编写一个程序从输入文件中读取数据,计算并报告每行和每列的总和。每行的总和表示该员工每周工作的小时数。每列的总和表示员工周一、周二等每天工作的累计小时数。最后输出总的小时数。针对上述文件hours.txt的输出结果见【输出示例】。
【输入】
文件hours.txt。(该文件已经存在,无需自己创建)
注意:本地调试程序时,则要求自己预先建立好hours.txt文件。在Windows下,可以使用记事本。
【输出】
员工每周工作的小时数。
员工周一、周二等每天工作的累计小时数。
最后输出总的小时数。
【输入示例】
文件hours.txt。
【输出示例】
Total hours = 40
Total hours = 40
Total hours = 32
Total hours = 25
Total hours = 16
Total hours = 16
Total hours = 32

Mon hours = 43
Tue hours = 32
Wed hours = 36
Thu hours = 40
Fri hours = 34
Sat hours = 8
Sun hours = 8
Total hours = 201
【提示】
文件hours.txt中数据组数是不定的。

(10分)
我的答案:
#include
#include
#include
#include
using namespace std;

int main(){
ifstream inFile;
string line;
int time[7]={0},t;
string m[8]={“Mon”,“Tue”,“Wed”,“Thu”,“Fri”,“Sat”,“Sun”,“Total”};

inFile.open("hours.txt");
if(!inFile.is_open()){
	exit(EXIT_FAILURE);
}
while(!inFile.eof()){
	getline(inFile,line);
	t=0;
	for(int i=0;i<line.length();i++){
		if(line[i]!=' '){
			t+=((int)line[i]-48);
			time[i/2]+=((int)line[i]-48);
		}
	} 
	cout<<"Total hours = "<<t<<endl;	 
}
cout<<endl;
t=0;
for(int i=0;i<7;i++){
	cout<<m[i]<<" hours = "<<time[i]<<endl;
	t+=time[i];
}
cout<<"Total hours = "<<t<<endl;
inFile.close();
return 0;

}
题目得分 10
参考答案:
#include
#include
#include
#include
#include
using namespace std;
const int DAYS = 7;
void process(ifstream &inFile);
// 将字符串line分离为数字存放在数组numbers中,并返回numbers中实际元素个数
int transferFrom(int numbers[], const string &line);
// 返回数组numbers的和(某员工每周工作时间的小时数)
int sum(int numbers[], int size);
// 统计员工每周每天工作累计小时数
void addTo(int total[], int numbers[]);
// 输出员工每周每天工作累计小时数和总的小时数
void print(int total[]);
int main() {
ifstream inFile;
inFile.open(“hours.txt”);
if(!inFile.is_open())
exit(EXIT_FAILURE);
process(inFile);
return 0;
}
void process(ifstream &inFile) {
int total[DAYS] = {0}; // 员工每周每天工作累计小时数
int numbers[DAYS] = {0}; // 某员工每周工作时间
int size;
while (!inFile.eof()) {
string line;
// 从文件中读取一行字符串
getline(inFile, line);
// 将字符串分离为数字
size = transferFrom(numbers, line);
cout << "Total hours = " << sum(numbers, size) << endl;
addTo(total, numbers);
}
cout << endl;
print(total);
}
int transferFrom(int numbers[], const string &line) {
int i = 0, j, value;
stringstream myStream(line);
while(myStream >> value) {
numbers[i] = value;
++i;
}
// 每行数据个数不同,Number数组后面没有数据的元素值设置为0
for(j = i; j < DAYS; ++j)
numbers[j] = 0;
return i;
}
int sum(int numbers[], int size) {
int s = 0;
for(int i = 0; i < size; ++i)
s += numbers[i];
return s;
}
void addTo(int total[], int numbers[]) {
for(int i = 0; i < DAYS; ++i)
total[i] += numbers[i];
}
void print(int total[]) {
string dayNames[] = {“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};
int s = 0;
for(int i = 0; i < DAYS; ++i) {
cout << dayNames[i] << " hours = " << total[i] << endl;
s += total[i];
}
cout << "Total hours = " << s << endl;
}
【描述】
处理日志文件,日志文件的储存格式为“年/月/日 时:分:秒 用户名 操作”。
日志文件有多条记录:
2015/4/218:00:33 37c3b6b58c6ac3 LOGIN
2015/4/218:15:35 11734e186f24fe4c LOGIN
2015/4/218:34:57 9f3cf331d19a9f LOGIN
2015/4/219:00:29 389bcca2159f5de7 LOGIN
2015/4/219:08:29 c3bde693fdb3c3d LOGIN
……
可以下载日志文件:
鼠标右键另存为
【输入】
日志文件log.txt。(该文件已经存在,无需自己创建)
【输出】
日志文件中活跃用户的数量。
【输入示例】

【输出示例】
123
【提示】
活跃用户指的是在日志文件中有过操作的用户,记得把重复出现的用户去掉。
输出示例只是格式说明,并非正确答案。

(10分)
我的答案:
#include
#include
#include
#include
using namespace std;
string ids[1000];
int main(){
ifstream inFile;
int year,month,day,hour,minute,second,count=0,flag;
char c;
string id,login;

inFile.open("log.txt");
if(!inFile.is_open()){
	exit(EXIT_FAILURE);
}

while(!inFile.eof()){
	inFile>>year>>c>>month>>c>>day;
	inFile>>hour>>c>>minute>>c>>second;
	inFile>>id;
	inFile>>login;
	flag=1;
	for(int i=0;i<count;i++){
		if(id==ids[i]){
			flag=-1;
			break;
		}
	}
	if(flag==1){
		ids[count]=id;
		count++;
	}
}	
cout<<count<<endl;
inFile.close();

return 0;

}
题目得分 10
参考答案:
#include
#include
#include
using namespace std;
int main() {
ifstream fin(“log.txt”);
int user_count = 0;
string ids[600];
while (!fin.eof()) {
int year, month, day, hour, minute, second;
char tmp;
string id, operation;
fin >> year >> tmp >> month >> tmp >> day;
fin >> hour >> tmp >> minute >> tmp >> second;
fin >> id;
fin >> operation;
int found = -1;
for(int i = 0; i < user_count; i++) {
if (id == ids[i]) {
found = i;
break;
}
}
if (found == -1)
ids[user_count++] = id;
}
fin.close();
cout << user_count << endl;
return 0;
}
【描述】
需要计算一些学生的加权平均分。给定输入文件gpa.dat,文件中每个学生的信息都由两行内容组成。第一行是学生姓名,第二行是他几门课的成绩。下面是某个输入文件gpa.dat的内容:
Zhang San
3 2.8 4 3.9 3 3.1
Li Si
3 3.9 3 4.0 4 3.9
Wang Wu
2 4.0 3 3.6 4 3.8 1 2.8
Liu Liu
3 3.0 4 2.9 3 3.2 2 2.5
例如,张三(Zhang San)同学:第一门课,学分3,成绩2.8;第二门课,学分4,成绩3.9;第三门课,学分3,成绩3.1。
总平均分等于学分乘以成绩,加权平均分等于总平均分除以总学分数。加权平均分最低0.0,最高4.0。
【输入】
文件gpa.dat。(该文件已经存在,无需自己创建)
注意:本地调试程序时,则要求自己预先建立好gpa.dat文件。在Windows下,可以使用记事本。
【输出】
在屏幕上显示每个学生的加权平均分以及加权平均分的最大和最小值。
【输入示例】
文件gpa.dat,注意:这里只给出了其中部分内容。
Zhang San
3 2.8 4 3.9 3 3.1
Li Si
3 3.9 3 4.0 4 3.9
Wang Wu
2 4.0 3 3.6 4 3.8 1 2.8
Liu Liu
3 3.0 4 2.9 3 3.2 2 2.5
【输出示例】
GPA for Zhang San = 3.33
GPA for Li Si = 3.93
GPA for Wang Wu = 3.68
GPA for Liu Liu = 2.93
max GPA = 3.93
min GPA = 2.93

(10分)
我的答案:
#include
#include
#include
#include
#include
#include
#include
using namespace std;

int main() {

fstream iof("gpa.dat",ios::in|ios::out|ios::binary);
if (!iof.is_open()) {
	cout << "不能打开文件" << endl;
	exit(EXIT_FAILURE);
}
string name,line;
double min = 5.0, max = -1;
while (getline(iof, line)) {
	name = line;
	getline(iof, line);
	double credit,score,creditN=0,scoreN=0,gpa;
	istringstream is(line);
	int n = 4;
    cout << "GPA for " << name << " = ";
	while (n--) {
		is >> credit>>score;
		creditN += credit;
		scoreN += score* credit;
	}
	gpa = scoreN / creditN;
	cout << fixed << setprecision(2) << gpa << endl;
	if (gpa > max) max = gpa;
	if (gpa < min) min = gpa;
}
cout << "max GPA = " << fixed<<setprecision(2) << max << endl;
cout << "min GPA = " << fixed << setprecision(2) << min << endl;
iof.close();
return 0;

}
题目得分 10
参考答案:
#include
#include
#include
#include
#include
#include
using namespace std;
void process(ifstream &inFile);
double processGrades(stringstream &myStream);
int main() {
ifstream inFile;
inFile.open(“gpa.dat”);
if (!inFile.is_open())
exit(EXIT_FAILURE);
process(inFile);
return 0;
}
void process(ifstream &inFile) {
double max = 0.0;
double min = 4.0;
while (!inFile.eof()) {
string name, grades;
getline(inFile, name);
getline(inFile, grades);
stringstream myStream(grades);
double gpa = processGrades(myStream);
cout << "GPA for " << name << " = "
<< fixed << setprecision(2) << gpa << endl;
if (gpa > max)
max = gpa;
if (gpa < min)
min = gpa;
}
cout << "max GPA = " << max << endl;
cout << "min GPA = " << min << endl;
}
double processGrades(stringstream &myStream) {
double totalQualityPoints = 0.0; // 总平均分
double totalUnits = 0.0; // 总学分数
double units, grade;
while (myStream >> units >> grade) {
totalUnits += units;
totalQualityPoints += units * grade;
}
if (totalUnits == 0.0)
return 0.0;
else
return totalQualityPoints / totalUnits;
}
【描述】
以二进制方式打开图片文件并读取该文件中的第 13(从1开始计数,后同),49, 80 个字节处的值,求这3个二进制数按位异或的结果(16进制表示)。
可以鼠标右键另存为下载图片文件:

【输入】
图片文件image.jpg。(该文件已经存在,无需自己创建)
【输出】
第 13(从1开始计数,后同),49, 80个字节处3个二进制数按位异或的结果(16进制表示)。
【输入示例】
图片文件image.jpg。
【输出示例】
a9
【提示】
输出示例只是格式说明,并非正确答案。

(10分)
我的答案:
#include
#include
using namespace std;
int main(){
ifstream inFile;
char b1,b2,b3;
inFile.open(“image.jpg”,ios::binary);
inFile.seekg(12,ios::beg);
inFile.read((char *)&b1,1);
inFile.seekg(48,ios::beg);
inFile.read((char *)&b2,1);
inFile.seekg(79,ios::beg);
inFile.read((char *)&b3,1);
cout<<hex<<((b1b2b3)&0x000000ff)<<endl;
inFile.close();

return 0;

}
题目得分 10
参考答案:
#include
#include
using namespace std;
int main() {
ifstream fin(“image.jpg”, ios::binary);
char byte1, byte2, byte3;
fin.seekg(12, ios::beg);
fin.read((char *)&byte1, 1);
fin.seekg(48, ios::beg);
fin.read((char *)&byte2, 1);
fin.seekg(79, ios::beg);
fin.read((char *)&byte3, 1);
cout << hex << ((byte1 ^ byte2 ^ byte3) & 0x000000ff) << endl;
return 0;
}
【描述】
输入一篇英文文章,求出现次数前三名的字母,不区分大小写(即出现A也计入出现a的次数中),按照次数由大到小输出,如果出现次数一样,按字典顺序输出。其它字符不予考虑。
附带说明:英文中,每个字母出现的频率是不一样的,在破译英文密码时,尤其是凯撒密码,统计每个字母出现的频率有着重要意义。
可以下载英文文章:
鼠标右键另存为
【输入】
英文文章news.txt。(文件有多行,该文件已经存在,无需自己创建)
【输出】
以如下格式:
字母:出现次数
显示出现次数前三名的字母和出现次数。
【输入示例】
英文文章news.txt。
【输出示例】
a:xxx
b:xx
c:xx
【提示】
输出示例只是格式说明,并非正确答案。

(10分)
我的答案:
#include
#include
#include
#include
#include
#include
using namespace std;
int main() {
int counts[26] = {0};
ifstream fin(“news.txt”);
string line;
while(getline(fin, line)) {
for(int i = 0; i < line.size(); ++i) {
if(isalpha(line[i])) {
if(isupper(line[i]))
line[i] = tolower(line[i]);
++counts[line[i] - ‘a’];
}
}
}
map<int, char, greater > m;
for(int i = 0; i < 26; ++i)
m.insert(make_pair(counts[i], static_cast(‘a’ + i)));
map<int, char>::iterator p = m.begin();
for(int i = 0; i < 3; ++i) {
cout << p->second << “:” << p->first << endl;
++p;
}
return 0;
}
题目得分 10
参考答案:
#include
#include
#include
#include
#include
#include
using namespace std;
int main() {
int counts[26] = {0};
ifstream fin(“news.txt”);
string line;
while(getline(fin, line)) {
for(int i = 0; i < line.size(); ++i) {
if(isalpha(line[i])) {
if(isupper(line[i]))
line[i] = tolower(line[i]);
++counts[line[i] - ‘a’];
}
}
}
map<int, char, greater > m;
for(int i = 0; i < 26; ++i)
m.insert(make_pair(counts[i], static_cast(‘a’ + i)));
map<int, char>::iterator p = m.begin();
for(int i = 0; i < 3; ++i) {
cout << p->second << “:” << p->first << endl;
++p;
}
return 0;
}
【描述】
声明并实现一个Student类,表示学生信息。Student类包括:
int类型的私有数据成员num,表示学号。
string类型的私有数据成员name,表示姓名。
int类型的私有数据成员score,表示成绩
char类型的私有数据成员grade,表示等级。
无参(默认)构造函数。
有参构造函数,将学号、姓名、成绩和等级设置为给定的参数。
访问器函数getNum、getName、getScore、getGrade,分别用于访问学号、姓名、成绩和等级。
重载流提取运算符>>和流插入运算符<<。输入输出一个Student对象
输入若干个学生的信息(学号、姓名和成绩),学号为0时,输入结束,根据成绩计算出对应等级。假设90分以上的成绩属于A级;80~89分、70~79分、60~69分的成绩分别属于B、C、D级;60分以下属于E级。创建Student对象,将它们写入文本文件student.txt中。
【输入】
输入若干个学生的信息。
每行一个学生信息,学号、姓名和成绩之间以空格间隔。
学号为0时,输入结束。
【输出】
文件student.txt。
不需要在屏幕上显示信息。
【输入示例】
100101 ZhangSan 78
100102 LiSi 67
100103 WangWu 83
100104 LiuLiu 45
100105 QianQi 93
0
【输出示例】
生成文件student.txt,其中内容:
100101 ZhangSan 78 C
100102 LiSi 67 D
100103 WangWu 83 B
100104 LiuLiu 45 E
100105 QianQi 93 A
【来源】
《程序设计基础——以C++为例》第8章实验3。(10分)
我的答案:
#include
#include
#include
#include
using namespace std;
class Student{
private:
int num,score;
string name;
char grade;
public:
Student(){
}
Student(int num,string name,int score,char grade){
this->name=name;
this->num=num;
this->score=score;
this->grade=grade;
}
int getNum(){
return num;
}
int getScore(){
return score;
}
string getName(){
return name;
}
char getGrade(){
return grade;
}friend ostream& operator<<(ostream& stream, const Student& x)
{
stream<< x.num << " " <<x.name<<" “<<x.score<<” "<<x.grade<<endl;
return stream;
}
};
int main() {
// ifstream inf(“plaintext.txt”);//读
// if (!inf.is_open()) {
// cout << “不能打开文件” << endl;
// exit(EXIT_FAILURE);
// }
ofstream outf(“student.txt”,ios::app);//写
if (!outf.is_open()) {
cout << “不能打开文件” << endl;
exit(EXIT_FAILURE);
}
int num,score;
string name;
char grade;
while(1){
cin>>num;
if(num==0)break;
cin>>name;
cin>>score;
if(score>=90)
grade=‘A’;
else if(score>=80)
grade=‘B’;
else if(score>=70)
grade=‘C’;
else if(score>=60)
grade=‘D’;
else
grade=‘E’;

	Student stu(num,name,score,grade);

// cout<< stu;
outf << stu;
}
// inf.close();
outf.close();
return 0;
}
题目得分 10
参考答案:
#include
#include
#include
#include
using namespace std;
class Student {
public:
Student() { }
Student(int num, string name, int score, char grade) {
this->num = num;
this->name = name;
this->score = score;
this->grade = grade;
}
int getNum() const {
return num;
}
string getName() const {
return name;
}
int getScore() const {
return score;
}
char getGrade() const {
return grade;
}
friend ostream &operator<<(ostream &out, const Student &student);
friend istream &operator>>(istream &in, Student &student);
private:
int num; // 学号
string name;// 姓名
int score; // 成绩
char grade; // 等级
};
ostream &operator<<(ostream &out, const Student &student) {
out << student.num << " " << student.name << " "
<< student.score << " " << student.grade << endl;
return out;
}
istream &operator>>(istream &in, Student &student) {
in >> student.num >> student.name >> student.score >> student.grade;
return in;
}
int main() {
ofstream outFile;
outFile.open(“student.txt”);
if(!outFile.is_open()) {
exit(EXIT_FAILURE);
}
int num;
string name;
int score;
char grade;
cin >> num;
while(num != 0) {
cin >> name >> score;
switch(score / 10) {
case 10:
case 9: grade = ‘A’;
break;
case 8: grade = ‘B’;
break;
case 7: grade = ‘C’;
break;
case 6: grade = ‘D’;
break;
default: grade = ‘E’;
break;
}
Student student(num, name, score, grade);
outFile << student;
cin >> num;
}
outFile.close();
return 0;
}
【描述】
将一个明文文件plaintext.txt中的内容,按照一定的方法,对每个字符加密后存放到另一个密文文件ciphertext.txt中。
【输入】
文件plaintext.txt。(该文件已经存在,无需自己创建)
注意:本地调试程序时,则要求自己预先建立好plaintext.txt文件。在Windows下,可以使用记事本。
【输出】
生成文件ciphertext.txt,里面存放加密后的信息。
不需要在屏幕上显示信息。
【输入示例】
文件plaintext.txt,假定其中内容如下:
Welcome to C++!
【输出示例】
生成文件ciphertext.txt,加密后的内容如下:
Ygneqog"vq"E–#
【提示】
这里采用一种简单的加密方法,将每个字符的编码加2。
【来源】
《程序设计基础——以C++为例》第8章实验2。(10分)
我的答案:
#include
#include
#include
using namespace std;
int main(){
ifstream inFile;
inFile.open(“plaintext.txt”);
ofstream outFile;
outFile.open(“ciphertext.txt”);
char c;
while(!inFile.eof()){
inFile.get©;
outFile.put(c+2);
}
inFile.close();
outFile.close();
return 0;
}
题目得分 10
参考答案:
#include
#include
#include
#include
using namespace std;
int main() {
const int CODING = 2;
ifstream inFile;
inFile.open(“plaintext.txt”);
if(!inFile.is_open()) {
exit(EXIT_FAILURE);
}
ofstream outFile;
outFile.open(“ciphertext.txt”);
if(!outFile.is_open()) {
exit(EXIT_FAILURE);
}
char ch;
inFile.get(ch);
while(!inFile.eof()) {
ch += CODING;
outFile.put(ch);
inFile.get(ch);
}
inFile.close();
outFile.close();
return 0;
}

【描述】
本章教材组合向量类Vector实现了一个Stack类模板。也可以用链表的方式实现栈。利用本章教材提供的链表类LinkedList,组合链表类LinkedList来实现一个新的Stack类模板。
template
class Stack {
public:
Stack();
void clear();
bool isEmpty() const;
void push(const T &value);
T pop();
T peek() const;
private:
LinkedList data;
};
【输入】
一系列正整数并入栈,输入-1表示结束,-1不是输入的数据的一部分。
【输出】
输出栈中所有的整数,每个整数后面跟一个空格以与后面的整数区分。
【输入示例】
1 3 5 2 -1
【输出示例】
2 5 3 1
【来源】
《程序设计基础——以C++为例》第9章实验4。

(20分)
我的答案:
/* 请在此处编写Stack类 */#include
#include
#include
using namespace std;
template
class Vector {
public:
Vector(int size); // 构造函数
Vector(int size, const T &value); // 构造函数
Vector(const Vector &v); // 拷贝构造函数
virtual ~Vector(); // 析构函数
const Vector &operator=(const Vector &right); // 重载赋值运算符
T &operator[](int index); // 重载下标运算符
T operator[](int index) const; // 重载下标运算符
int getSize() const;
void resize(int size);
private:
T *pVector; // 指针,指向存放数组元素的动态分配内存空间
int size; // 数组长度
};
template
Vector::Vector(int size) {
if(size > 0)
this->size = size;
else
throw invalid_argument(“数组长度必须是正整数!”);
pVector = new T[size];
}
template
Vector::Vector(int size, const T &value) {
if(size > 0)
this->size = size;
else
throw invalid_argument(“数组长度必须是正整数!”);
pVector = new T[size];
for(int i = 0; i < size; ++i)
pVector[i] = value;
}
template
Vector::Vector(const Vector &v) {
size = v.size;
pVector = new T[size];
for(int i = 0; i < size; ++i)
pVector[i] = v.pVector[i];
}
template
Vector::~Vector() {
delete[] pVector;
}
template
const Vector &Vector::operator=(const Vector &right) {
if(this != &right) {
if(size != right.size) {
delete[] pVector;
size = right.size;
pVector = new T[size];
}
for(int i = 0; i < size; ++i)
pVector[i] = right.pVector[i];
}
return this;
}
template
T &Vector::operator[](int index) {
if(index < 0 || index > size - 1)
throw out_of_range(“数组下标超出允许范围!”);
return pVector[index];
}
template
T Vector::operator[](int index) const {
if(index < 0 || index > size - 1)
throw out_of_range(“数组下标超出允许范围!”);
return pVector[index];
}
template
int Vector::getSize() const {
return size;
}
template
void Vector::resize(int size) {
if(size > 0) {
if(this->size != size) {
T old = pVector;
pVector = new T[size];
int newSize = (this->size > size) ? size : this->size;
for(int i = 0; i < newSize; ++i)
pVector[i] = old[i];
this->size = size;
delete[] old;
}
}
else
throw invalid_argument(“数组长度必须是正整数!”);
}
template
class Stack {
public:
Stack(int size = 16); // 构造函数
Stack(const Stack &v); // 拷贝构造函数
void clear(); // 将栈设置为空栈
bool isEmpty() const; // 判断栈是否为空
void push(T value); // 入栈
T pop(); // 出栈
T peek() const; // 获取栈顶元素
private:
Vector data; // 存放栈元素
int top; // 记录栈顶位置
};
template
Stack::Stack(int size):data(size) {
clear();
}
template
Stack::Stack(const Stack &v)
:data(v.data), top(v.top) { }
template
void Stack::clear() {
top = 0;
}
template
bool Stack::isEmpty() const {
return top == 0;
}
template
void Stack::push(T value) {
if(top >= data.getSize())
data.resize(2 * data.getSize());
data[top++] = value;
}
template
T Stack::pop() {
return data[–top];
}
template
T Stack::peek() const {
return data[top - 1];
}
class PostfixEvaluation {
public:
PostfixEvaluation(const string &postfixExpression); // 构造函数
string getPostfixExpression() const; // 获取后缀表达式
void setPostfixExpression(const string &postfixExpression); // 设置后缀表达式
int evaluate(); // 计算并返回后缀表达式值
private:
string postfixExpression; // 存放要计算的后缀表达式
Stack operandStack; // 存放操作数
void getOperands(int &left, int &right); // 操作数出栈
int calculate(int left, int right, char op) const; // 求操作数运算值
bool isOperator(char ch) const; // 是否是运算符
};
void PostfixEvaluation::getOperands(int &left, int &right) {
if(operandStack.isEmpty())
throw runtime_error(“Too many operators!”);
right = operandStack.pop();
if(operandStack.isEmpty())
throw runtime_error(“Too many operators!”);
left = operandStack.pop();
}
int PostfixEvaluation::calculate(int left, int right, char op) const {
int value;
switch(op) {
case ‘+’:value = left + right;
break;
case ‘-’:value = left - right;
break;
case '
’:value = left * right;
break;
case ‘/’:if(right == 0)
throw runtime_error(“Divisor cannot be zero!”);
value = left / right;
break;
case ‘%’:if(right == 0)
throw runtime_error(“Divisor cannot be zero!”);
value = left % right;
break;
}
return value;
}
bool PostfixEvaluation::isOperator(char ch) const {
return ch == ‘+’ || ch == ‘-’ || ch == '
’ || ch == ‘/’ || ch == ‘%’;
}
PostfixEvaluation::PostfixEvaluation(const string &postfixExpression) {
this->postfixExpression = postfixExpression;
}
string PostfixEvaluation::getPostfixExpression() const {
return postfixExpression;
}
void PostfixEvaluation::setPostfixExpression(const string &postfixExpression) {
this->postfixExpression = postfixExpression;
}
int PostfixEvaluation::evaluate() {
int left, right, value;
char ch;
for(string::size_type i = 0; i < postfixExpression.size(); ++i) {
ch = postfixExpression[i];
if(isdigit(ch))
operandStack.push(ch - ‘0’);
else if(isOperator(ch)) {
getOperands(left, right);
operandStack.push(calculate(left, right, ch));
}
else if(!isspace(ch))
throw runtime_error(“Illegal input!”);
}
value = operandStack.pop();
if(!operandStack.isEmpty())
throw runtime_error(“Too many operands!”);
return value;
}
题目得分 20
参考答案:
#include
#include
using namespace std;
template
class Node {
public:
Node() {
next = NULL;
}
Node(const T &value) {
this->value = value;
next = NULL;
}
T value;
Node *next;
};
template
class LinkedList {
public:
LinkedList();
void addFirst(const T &value);
void addLast(const T &value);
void add(int index, const T &value);
void removeFirst();
void removeLast();
void removeAt(int index);
T getFirst() const;
T getLast() const;
void clear();
bool isEmpty() const;
int getSize() const;
void print() const;
private:
Node *head, *tail;
int size;
};
template
LinkedList::LinkedList() {
head = tail = NULL;
size = 0;
}
template
void LinkedList::addFirst(const T &value) {
Node *temp = new Node(value);
temp->next = head;
head = temp;
++size;
if(tail == NULL)
tail = head;
}
template
void LinkedList::addLast(const T &value) {
if(tail == NULL)
head = tail = new Node(value);
else {
tail->next = new Node(value);
tail = tail->next;
}
++size;
}
template
void LinkedList::add(int index, const T &value) {
if(index == 0)
addFirst(value);
else if(index >= size)
addLast(value);
else {
Node *current = head;
for(int i = 1; i < index; ++i)
current = current->next;
Node *temp = current->next;
current->next = new Node(value);
current->next->next = temp;
++size;
}
}
template
void LinkedList::removeFirst() {
if(head == NULL)
throw runtime_error(“空链表!”);
else {
Node *temp = head;
head = head->next;
if(head == NULL)
tail = NULL;
delete temp;
–size;
}
}
template
void LinkedList::removeLast() {
if(tail == NULL)
throw runtime_error(“空链表!”);
else if(head == tail) {
Node *temp = head;
head = tail = NULL;
size = 0;
delete temp;
}
else {
Node *current = head;
while(current->next != tail)
current = current->next;
Node *temp = tail;
tail = current;
tail->next = NULL;
delete temp;
–size;
}
}
template
void LinkedList::removeAt(int index) {
if(index < 0 || index >= size)
throw runtime_error(“下标越界!”);
else if(index == 0)
return removeFirst();
else if(index == size - 1)
return removeLast();
else {
Node *previous = head;
for(int i = 1; i < index; ++i)
previous = previous->next;
Node *current = previous->next;
previous->next = current->next;
delete current;
–size;
}
}
template
T LinkedList::getFirst() const {
if(head == NULL)
throw runtime_error(“空链表!”);
else
return head->value;
}
template
T LinkedList::getLast() const {
if(tail == NULL)
throw runtime_error(“空链表!”);
else
return tail->value;
}
template
void LinkedList::clear() {
while(head != NULL) {
Node *temp = head;
head = head->next;
delete temp;
}
tail = NULL;
}
template
bool LinkedList::isEmpty() const {
return head == NULL;
}
template
int LinkedList::getSize() const {
return size;
}
template
void LinkedList::print() const {
Node *current = head;
while(current != NULL) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
}
template
class Stack {
public:
Stack();
void clear();
bool isEmpty() const;
void push(const T &value);
T pop();
T peek() const;
private:
LinkedList data;
};
template
Stack::Stack() { }
template
void Stack::clear() {
data.clear();
}
template
bool Stack::isEmpty() const {
return data.isEmpty();
}
template
void Stack::push(const T &value) {
data.addLast(value);
}
template
T Stack::pop() {
T temp = data.getLast();
data.removeLast();
return temp;
}
template
T Stack::peek() const {
return data.getLast();
}
int main() {
Stack intStack;
int num;
cin >> num;
while(num != -1) {
intStack.push(num);
cin >> num;
}
while(!intStack.isEmpty())
cout << intStack.pop() << " ";
cout << endl;
return 0;
}
【描述】
编写程序,输入若干个正整数,输入-1时输入结束,可以简化修改本章教材提供的链表类LinkedList,用单向链表组织输入的正整数。要求链表按照结点中整数值的大小从大到小排序,不包括最后标识结束的-1。输出单向链表。
【输入】
一系列正整数,输入-1表示结束,-1不是输入的数据的一部分。
【输出】
按照结点中整数值的大小从大到小输出所有的整数,每个整数后面跟一个空格以与后面的整数区分,最后的整数后面没有空格。
【输入示例】
1 3 5 2 -1
【输出示例】
5 3 2 1
【来源】
《程序设计基础——以C++为例》第9章实验3。

(20分)
我的答案:
template
class Node {
public:
Node() {
next = NULL;
}
Node(const T &value) {
this->value = value;
next = NULL;
}
T value;
Node *next;
};
template
class LinkedList {
public:
LinkedList();
void add(const T &value);
void print() const;
private:
Node *head;
int size;
};
template
LinkedList::LinkedList() {
head = NULL;
size = 0;
}
template
void LinkedList::add(const T &value) {
Node *temp = new Node(value);
Node *current = head;
Node *previous = NULL;
while(current != NULL && current->value > value) {
previous = current;
current = current->next;
}
if(current == head)
head = temp;
else
previous->next = temp;
temp->next = current;
++size;
}
template
void LinkedList::print() const {
Node *current = head;
while(current != NULL) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
}
题目得分 20
参考答案:
#include
using namespace std;
template
class Node {
public:
Node() {
next = NULL;
}
Node(const T &value) {
this->value = value;
next = NULL;
}
T value;
Node *next;
};
template
class LinkedList {
public:
LinkedList();
void add(const T &value);
void print() const;
private:
Node *head;
int size;
};
template
LinkedList::LinkedList() {
head = NULL;
size = 0;
}
template
void LinkedList::add(const T &value) {
Node *temp = new Node(value);
Node *current = head;
Node *previous = NULL;
while(current != NULL && current->value > value) {
previous = current;
current = current->next;
}
if(current == head)
head = temp;
else
previous->next = temp;
temp->next = current;
++size;
}
template
void LinkedList::print() const {
Node current = head;
while(current != NULL) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
}
int main() {
LinkedList list;
int num;
cin >> num;
while(num > 0) {
list.add(num); // 输入的正整数按从大到小的顺序添加到链表中
cin >> num;
}
list.print(); // 输出链表
return 0;
}
【描述】
给定一个链表,链表的每个节点只含有一个int型元素和Node
指针,该链表共有十个节点,输出链表元素值为奇数的项。部分代码已经写好,请补全output函数即可。
【输入】
输入10个整数。
【输出】
输出奇数值,以空格隔开。
【输入示例】
1 3 4 5 6 7 8 10 11 15
【输出示例】
1 3 5 7 11 15

(20分)
我的答案:
Node *p = head;
while(p != NULL) {
if(p->value % 2 != 0)
cout << p->value << " ";
p = p->next;
}
题目得分 20
参考答案:
#include
using namespace std;
class Node {
public:
int value;
Node *next;
Node() { }
Node(int x) : value(x), next(NULL) { }
};
class SingleLinkedList {
public:
SingleLinkedList() {
head = NULL;
}
void init() { // 链表初始化
int val;
cin >> val;
head = new Node(val);
Node *tmpNode = head;
for(int i = 0; i < 9; i++) { // 链表共有10个节点,head后还有9个
cin >> val;
Node pNode = new Node(val);
tmpNode->next = pNode;
tmpNode = pNode;
}
tmpNode->next = NULL;
}
void output() { // 输出链表
Node p = head;
while(p != NULL) {
if(p->value % 2 != 0)
cout << p->value << " ";
p = p->next;
}
}
private:
Node head;
};
int main() {
SingleLinkedList list;
list.init();
list.output();
return 0;
}
【描述】
栈可以应用于算术表达式求值。这里对算术表达式做如下简化:运算符为+、-、
、/、%;操作数为单数字(0~9)非负整数。
例如:
(2+5)3-8/3
上述形式的算术表达式也称中缀表达式,因为每个运算符出现在它的两个操作数之间。编译器在求算术表达式值时,往往将中缀表达式转换为后缀表达式。后缀表达式也称逆波兰表达式,由波兰数学家Jan Lukasiewicz发明,指运算符出现在操作数后面的不含括号的算术表达式。
中缀表达式:a+b
c,其后缀表达式为:a b c * +。因为
的优先级比+高,所以先计算b
c,即b c *;+的操作数是a和b c *,即a b c * +。
中缀表达式:(a+b)*c,其后缀表达式为:a b + c 。先计算圆括号中a+b,即a b +;的操作数是a b +和c,即a b + c
中缀表达式:(a
b+c)/d+e,其后缀表达式为:a b * c + d / e +。先计算圆括号中a
b+c,即a b * c +;/的操作数是a b * c +和d,即a b * c + d /;+的操作数是a b * c + d /和e,即a b * c + d / e +。
后缀表达式求值使用一个存放操作数的栈。求值过程顺序扫描后缀表达式,每次遇到操作数就将它入栈;遇到运算符时,就从栈中弹出两个操作数进行计算,并将结果入栈。到扫描结束,留在栈顶的操作数就是所求算术表达式的值。
例如:
4 2 7 +
如下图一所示,顺序读取操作数4、2、7,并入栈。如下图二所示,读取运算符
,操作数7、2出栈,计算2
7,结果为14并入栈。如下图三所示,读取运算符+,操作数14、4出栈,计算4+14,结果为18并入栈。扫描后缀表达式后,栈中惟一元素即为最终结果。

本章教材组合向量类Vector实现了一个Stack类模板。请组合栈类Stack,声明并实现一个PostfixEvaluation类,求后缀表达式的值。PostfixEvaluation类包括:

string类型的私有数据成员postfixExpression,存放后缀表达式。
Stack类型的私有数据成员operandStack,存放操作数(单数字非负整数)。
私有成员函数getOperands,连续从栈顶出栈两个操作数。
私有成员函数calculate,求出栈的两个操作数的计算结果,并将结果入栈。
私有成员函数isOperator,确定输入的运算符是有效运算符(+、-、*、/、%)
有参构造函数。新建一个后缀表达式对象。
访问器函数getPostfixExpression,获取后缀表达式。
更改器函数setPostfixExpression,设置新的后缀表达式。
成员函数evaluate,计算并返回后缀表达式的值。
PostfixEvaluation类如下:
class PostfixEvaluation {
public:
PostfixEvaluation(const string&postfixExpression); // 构造函数
stringgetPostfixExpression() const; // 获取后缀表达式
void setPostfixExpression(const string&postfixExpression); // 设置后缀表达式
int evaluate(); // 计算并返回后缀表达式值
private:
string postfixExpression; // 存放要计算的后缀表达式
Stack operandStack; // 存放操作数
void getOperands(int &left, int&right); // 操作数出栈
int calculate(int left, int right, char op) const; // 求操作数运算值
bool isOperator(char ch) const; // 是否是运算符
};
【输入】
输入一个后缀表达式。
【输出】
输出后缀表达式的值。
【输入示例1】
4 2 7 * +
【输出示例1】
18
【输入示例2】
8 4 0 % +
【输出示例2】
Divisor cannot be zero!
【输入示例3】
2 3 ^ 4 +
【输出示例3】
Illegal input!
【输入示例4】
4 2 / *
【输出示例4】
Too many operators!
【输入示例5】
1 2 3 +
【输出示例5】
Too many operands!
【来源】
《程序设计基础——以C++为例》第9章实验2。

(20分)
我的答案:
class PostfixEvaluation {
public:
PostfixEvaluation(const string &postfixExpression); // 构造函数
string getPostfixExpression() const; // 获取后缀表达式
void setPostfixExpression(const string &postfixExpression); // 设置后缀表达式
int evaluate(); // 计算并返回后缀表达式值
private:
string postfixExpression; // 存放要计算的后缀表达式
Stack operandStack; // 存放操作数
void getOperands(int &left, int &right); // 操作数出栈
int calculate(int left, int right, char op) const; // 求操作数运算值
bool isOperator(char ch) const; // 是否是运算符
};
void PostfixEvaluation::getOperands(int &left, int &right) {
if(operandStack.isEmpty())
throw runtime_error(“Too many operators!”);
right = operandStack.pop();
if(operandStack.isEmpty())
throw runtime_error(“Too many operators!”);
left = operandStack.pop();
}
int PostfixEvaluation::calculate(int left, int right, char op) const {
int value;
switch(op) {
case ‘+’:value = left + right;
break;
case ‘-’:value = left - right;
break;
case ‘’:value = left * right;
break;
case ‘/’:if(right == 0)
throw runtime_error(“Divisor cannot be zero!”);
value = left / right;
break;
case ‘%’:if(right == 0)
throw runtime_error(“Divisor cannot be zero!”);
value = left % right;
break;
}
return value;
}
bool PostfixEvaluation::isOperator(char ch) const {
return ch == ‘+’ || ch == ‘-’ || ch == '
’ || ch == ‘/’ || ch == ‘%’;
}
PostfixEvaluation::PostfixEvaluation(const string &postfixExpression) {
this->postfixExpression = postfixExpression;
}
string PostfixEvaluation::getPostfixExpression() const {
return postfixExpression;
}
void PostfixEvaluation::setPostfixExpression(const string &postfixExpression) {
this->postfixExpression = postfixExpression;
}
int PostfixEvaluation::evaluate() {
int left, right, value;
char ch;
for(string::size_type i = 0; i < postfixExpression.size(); ++i) {
ch = postfixExpression[i];
if(isdigit(ch))
operandStack.push(ch - ‘0’);
else if(isOperator(ch)) {
getOperands(left, right);
operandStack.push(calculate(left, right, ch));
}
else if(!isspace(ch))
throw runtime_error(“Illegal input!”);
}
value = operandStack.pop();
if(!operandStack.isEmpty())
throw runtime_error(“Too many operands!”);
return value;
}
题目得分 20
参考答案:
#include
#include
#include
using namespace std;
template
class Vector {
public:
Vector(int size); // 构造函数
Vector(int size, const T &value); // 构造函数
Vector(const Vector &v); // 拷贝构造函数
virtual ~Vector(); // 析构函数
const Vector &operator=(const Vector &right); // 重载赋值运算符
T &operator[](int index); // 重载下标运算符
T operator[](int index) const; // 重载下标运算符
int getSize() const;
void resize(int size);
private:
T *pVector; // 指针,指向存放数组元素的动态分配内存空间
int size; // 数组长度
};
template
Vector::Vector(int size) {
if(size > 0)
this->size = size;
else
throw invalid_argument(“数组长度必须是正整数!”);
pVector = new T[size];
}
template
Vector::Vector(int size, const T &value) {
if(size > 0)
this->size = size;
else
throw invalid_argument(“数组长度必须是正整数!”);
pVector = new T[size];
for(int i = 0; i < size; ++i)
pVector[i] = value;
}
template
Vector::Vector(const Vector &v) {
size = v.size;
pVector = new T[size];
for(int i = 0; i < size; ++i)
pVector[i] = v.pVector[i];
}
template
Vector::~Vector() {
delete[] pVector;
}
template
const Vector &Vector::operator=(const Vector &right) {
if(this != &right) {
if(size != right.size) {
delete[] pVector;
size = right.size;
pVector = new T[size];
}
for(int i = 0; i < size; ++i)
pVector[i] = right.pVector[i];
}
return this;
}
template
T &Vector::operator[](int index) {
if(index < 0 || index > size - 1)
throw out_of_range(“数组下标超出允许范围!”);
return pVector[index];
}
template
T Vector::operator[](int index) const {
if(index < 0 || index > size - 1)
throw out_of_range(“数组下标超出允许范围!”);
return pVector[index];
}
template
int Vector::getSize() const {
return size;
}
template
void Vector::resize(int size) {
if(size > 0) {
if(this->size != size) {
T old = pVector;
pVector = new T[size];
int newSize = (this->size > size) ? size : this->size;
for(int i = 0; i < newSize; ++i)
pVector[i] = old[i];
this->size = size;
delete[] old;
}
}
else
throw invalid_argument(“数组长度必须是正整数!”);
}
template
class Stack {
public:
Stack(int size = 16); // 构造函数
Stack(const Stack &v); // 拷贝构造函数
void clear(); // 将栈设置为空栈
bool isEmpty() const; // 判断栈是否为空
void push(T value); // 入栈
T pop(); // 出栈
T peek() const; // 获取栈顶元素
private:
Vector data; // 存放栈元素
int top; // 记录栈顶位置
};
template
Stack::Stack(int size):data(size) {
clear();
}
template
Stack::Stack(const Stack &v)
:data(v.data), top(v.top) { }
template
void Stack::clear() {
top = 0;
}
template
bool Stack::isEmpty() const {
return top == 0;
}
template
void Stack::push(T value) {
if(top >= data.getSize())
data.resize(2 * data.getSize());
data[top++] = value;
}
template
T Stack::pop() {
return data[–top];
}
template
T Stack::peek() const {
return data[top - 1];
}
class PostfixEvaluation {
public:
PostfixEvaluation(const string &postfixExpression); // 构造函数
string getPostfixExpression() const; // 获取后缀表达式
void setPostfixExpression(const string &postfixExpression); // 设置后缀表达式
int evaluate(); // 计算并返回后缀表达式值
private:
string postfixExpression; // 存放要计算的后缀表达式
Stack operandStack; // 存放操作数
void getOperands(int &left, int &right); // 操作数出栈
int calculate(int left, int right, char op) const; // 求操作数运算值
bool isOperator(char ch) const; // 是否是运算符
};
void PostfixEvaluation::getOperands(int &left, int &right) {
if(operandStack.isEmpty())
throw runtime_error(“Too many operators!”);
right = operandStack.pop();
if(operandStack.isEmpty())
throw runtime_error(“Too many operators!”);
left = operandStack.pop();
}
int PostfixEvaluation::calculate(int left, int right, char op) const {
int value;
switch(op) {
case ‘+’:value = left + right;
break;
case ‘-’:value = left - right;
break;
case '
’:value = left * right;
break;
case ‘/’:if(right == 0)
throw runtime_error(“Divisor cannot be zero!”);
value = left / right;
break;
case ‘%’:if(right == 0)
throw runtime_error(“Divisor cannot be zero!”);
value = left % right;
break;
}
return value;
}
bool PostfixEvaluation::isOperator(char ch) const {
return ch == ‘+’ || ch == ‘-’ || ch == '
’ || ch == ‘/’ || ch == ‘%’;
}
PostfixEvaluation::PostfixEvaluation(const string &postfixExpression) {
this->postfixExpression = postfixExpression;
}
string PostfixEvaluation::getPostfixExpression() const {
return postfixExpression;
}
void PostfixEvaluation::setPostfixExpression(const string &postfixExpression) {
this->postfixExpression = postfixExpression;
}
int PostfixEvaluation::evaluate() {
int left, right, value;
char ch;
for(string::size_type i = 0; i < postfixExpression.size(); ++i) {
ch = postfixExpression[i];
if(isdigit(ch))
operandStack.push(ch - ‘0’);
else if(isOperator(ch)) {
getOperands(left, right);
operandStack.push(calculate(left, right, ch));
}
else if(!isspace(ch))
throw runtime_error(“Illegal input!”);
}
value = operandStack.pop();
if(!operandStack.isEmpty())
throw runtime_error(“Too many operands!”);
return value;
}
int main() {
string expression;
getline(cin, expression);
PostfixEvaluation exp(expression);
try {
cout << exp.evaluate() << endl;
}
catch(runtime_error &ex) {
cout << ex.what() << endl;
}
return 0;
}
【描述】
矩阵是数学里的一种抽象对象,可以用C++提供的静态数组来表示矩阵,其大小在编译时就已经确定,在运行时无法修改,而且不检查下标是否越界。可以利用教材本章提供的向量类Vector,用向量的方式实现矩阵,用一个指针向量来表示矩阵,其中的每个指针又各指向一个向量,用它们来表示矩阵的行向量。矩阵的逻辑结构如下图所示。

组合向量类Vector,声明并实现一个Matrix类模板,表示矩阵。Matrix类模板包括:

Vector类型的私有数据成员rows,存放矩阵元素。
构造函数,将矩阵的行、列大小设置为给定的参数。
构造函数,将矩阵的行、列大小设置为给定的参数,给矩阵元素赋相同的初始值。
重载下标运算符[]。
访问器函数getRows,用于获取矩阵行数。
访问器函数getColumns,用于获取矩阵列数。
Matrix类模板如下:
template
class Matrix {
public:
Matrix(int row, int column);
Matrix(int row, int column, const T &value);
Vector &operator[](int index);
Vector operator[](int index) const;
int getRows() const;
int getColumns() const;
private:
Vector<Vector*> rows; // 存放矩阵元素
};

以普通函数的形式重载运算符函数,实现矩阵乘法。
template
Matrix operator
(const Matrix &lhs, const Matrix &rhs);

printMatrix函数输出矩阵的值。
template
void printMatrix(const Matrix &m);
【输入】
输入3×3矩阵a和矩阵b。
【输出】
矩阵a乘以矩阵b的结果。每个元素输出宽度为4。
【输入示例】
1 1 7
7 5 6
9 6 1
6 1 6
4 1 5
1 5 1
【输出示例】

17 37 18
68 42 73
79 20 85
【来源】
《程序设计基础——以C++为例》第9章实验1。

(20分)
我的答案:
template
class Matrix {
public:
Matrix(int row, int column); // 构造函数
Matrix(int row, int column, const T &value); // 构造函数
Vector &operator[](int index); // 重载下标运算符
Vector operator[](int index) const; // 重载下标运算符
int getRows() const;
int getColumns() const;
private:
Vector<Vector*> rows; // 存放矩阵元素
};
template
Matrix::Matrix(int row, int column):rows(row) {
for(int i = 0; i < row; ++i)
rows[i] = new Vector(column);
}
template
Matrix::Matrix(int row, int column, const T &value):rows(row) {
for(int i = 0; i < row; ++i)
rows[i] = new Vector(column, value);
}
template
Vector &Matrix::operator[](int index) {
return *rows[index];
}
template
Vector Matrix::operator[](int index) const {
return rows[index];
}
template
int Matrix::getRows() const {
return rows.getSize();
}
template
int Matrix::getColumns() const {
return rows[0]->getSize();
}
template
Matrix operator
(const Matrix &lhs, const Matrix &rhs) {
int lhsRow = lhs.getRows();
int lhsColumn = lhs.getColumns();
int rhsColumn = rhs.getColumns();
Matrix result(lhsRow, rhsColumn, 0);
for(int i = 0; i < lhsRow; ++i) {
for(int j = 0; j < rhsColumn; ++j) {
for(int k = 0; k < lhsColumn; ++k)
result[i][j] += lhs[i][k] * rhs[k][j];
}
}
return result;
}
template
void printMatrix(const Matrix &m) {
int row = m.getRows();
int column = m.getColumns();
for(int i = 0; i < row; ++i) {
for(int j = 0; j < column; ++j)
cout << setw(4) << m[i][j];
cout << endl;
}
}
题目得分 20
参考答案:
#include
#include
#include
using namespace std;
template
class Vector {
public:
Vector(int size); // 构造函数
Vector(int size, const T &value); // 构造函数
Vector(const Vector &v); // 拷贝构造函数
virtual ~Vector(); // 析构函数
const Vector &operator=(const Vector &right); // 重载赋值运算符
T &operator[](int index); // 重载下标运算符
T operator[](int index) const; // 重载下标运算符
int getSize() const;
void resize(int size);
private:
T *pVector; // 指针,指向存放数组元素的动态分配内存空间
int size; // 数组长度
};
template
Vector::Vector(int size) {
if(size > 0)
this->size = size;
else
throw invalid_argument(“数组长度必须是正整数!”);
pVector = new T[size];
}
template
Vector::Vector(int size, const T &value) {
if(size > 0)
this->size = size;
else
throw invalid_argument(“数组长度必须是正整数!”);
pVector = new T[size];
for(int i = 0; i < size; ++i)
pVector[i] = value;
}
template
Vector::Vector(const Vector &v) {
size = v.size;
pVector = new T[size];
for(int i = 0; i < size; ++i)
pVector[i] = v.pVector[i];
}
template
Vector::~Vector() {
delete[] pVector;
}
template
const Vector &Vector::operator=(const Vector &right) {
if(this != &right) {
if(size != right.size) {
delete[] pVector;
size = right.size;
pVector = new T[size];
}
for(int i = 0; i < size; ++i)
pVector[i] = right.pVector[i];
}
return *this;
}
template
T &Vector::operator[](int index) {
if(index < 0 || index > size - 1)
throw out_of_range(“数组下标超出允许范围!”);
return pVector[index];
}
template
T Vector::operator[](int index) const {
if(index < 0 || index > size - 1)
throw out_of_range(“数组下标超出允许范围!”);
return pVector[index];
}
template
int Vector::getSize() const {
return size;
}
template
void Vector::resize(int size) {
if(size > 0) {
if(this->size != size) {
T old = pVector;
pVector = new T[size];
int newSize = (this->size > size) ? size : this->size;
for(int i = 0; i < newSize; ++i)
pVector[i] = old[i];
this->size = size;
delete[] old;
}
}
else
throw invalid_argument(“数组长度必须是正整数!”);
}
template
class Matrix {
public:
Matrix(int row, int column); // 构造函数
Matrix(int row, int column, const T &value); // 构造函数
Vector &operator[](int index); // 重载下标运算符
Vector operator[](int index) const; // 重载下标运算符
int getRows() const;
int getColumns() const;
private:
Vector<Vector
> rows; // 存放矩阵元素
};
template
Matrix::Matrix(int row, int column):rows(row) {
for(int i = 0; i < row; ++i)
rows[i] = new Vector(column);
}
template
Matrix::Matrix(int row, int column, const T &value):rows(row) {
for(int i = 0; i < row; ++i)
rows[i] = new Vector(column, value);
}
template
Vector &Matrix::operator[](int index) {
return *rows[index];
}
template
Vector Matrix::operator[](int index) const {
return rows[index];
}
template
int Matrix::getRows() const {
return rows.getSize();
}
template
int Matrix::getColumns() const {
return rows[0]->getSize();
}
template
Matrix operator
(const Matrix &lhs, const Matrix &rhs) {
int lhsRow = lhs.getRows();
int lhsColumn = lhs.getColumns();
int rhsColumn = rhs.getColumns();
Matrix result(lhsRow, rhsColumn, 0);
for(int i = 0; i < lhsRow; ++i) {
for(int j = 0; j < rhsColumn; ++j) {
for(int k = 0; k < lhsColumn; ++k)
result[i][j] += lhs[i][k] * rhs[k][j];
}
}
return result;
}
template
void printMatrix(const Matrix &m) {
int row = m.getRows();
int column = m.getColumns();
for(int i = 0; i < row; ++i) {
for(int j = 0; j < column; ++j)
cout << setw(4) << m[i][j];
cout << endl;
}
}
int main() {
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 3;
Matrix a(ROW_SIZE, COLUMN_SIZE);
Matrix b(ROW_SIZE, COLUMN_SIZE);
for(int i = 0; i < ROW_SIZE; ++i) {
for(int j = 0; j < COLUMN_SIZE; ++j) {
cin >> a[i][j];
}
}
for(int i = 0; i < ROW_SIZE; ++i) {
for(int j = 0; j < COLUMN_SIZE; ++j) {
cin >> b[i][j];
}
}
printMatrix(a * b);
return 0;
}

【描述】
求一个正整数各位数字之和。要求定义和调用函数:int sumDigits(int n),该函数返回一个正整数各位数字之和。
【输入】
输入一个正整数。
【输出】
输出该正整数各位数字之和。
【输入示例】
3456
【输出示例】
18
【来源】
《程序设计基础——以C++为例》第3章实验2强化练习。(10分)
我的答案:
int sumDigits(int n){
int c=0;
while(n!=0){
c+=n%10;
n=n/10;
}
return c;
}
题目得分
参考答案:
#include
using namespace std;
int sumDigits(int n);
int main() {
int n;
cin >> n;
cout << sumDigits(n) << endl;
return 0;
}
int sumDigits(int n) {
int remainder, result = 0;
while (n != 0) {
remainder = n % 10;
result += remainder;
n = n / 10;
}
return result;
}
【描述】
输入整数n(0<=n<=100000),以及整数i,j(0<=i、j<31,且i不等于j),输出整数k,要求:
①k的第i位和n相同;
②第j位和n不同;
③其他位都是0。
这里提到的位,指的是将n表示成二进制数后的位,最低位(最右边)是第0位
【输入】
第一行是整数t,表示数据组数。
每组输入数据一行,包含三个整数n,i和j。
【输出】
对每组输入数据,输出一行:符合题目要求的整数k。
【样例输入】
2
23 4 3
3 0 1
【样例输出】
24
1
(10分)
我的答案:
#include
#include
using namespace std;
int main(){
int t,n,i,j,N;
cin>>t;
while(t–){
int k=0,e=0;
cin>>n>>i>>j;
N=n;
for(int p=0;p<=i;p++){
e=N%2;
N=N/2;
}
k+=epow(2,i);
N=n;
for(int p=0;p<=j;p++){
e=N%2;
N=N/2;
}
k+=(1-e)pow(2,j);
cout<<k<<endl;
}
return 0;
}
题目得分
参考答案:
#include
using namespace std;
int main() {
int t;
cin >> t;
while(t–) {
int n, i, j;
cin >> n >> i >> j;
// 第j位和n不同
int m = ( 1 << j ) ^ n;
// 第i位和n相同
int k = ((1 << i) & n) | ((1 << j) & m);
cout << k << endl;
}
return 0;
}
【描述】
输入若干学生信息,把他们的名字按成绩从低到高排序输出。
【输入】
第一行是整数 t,表示数据组数。
每组输入数据第一行是整数n,表示学生的数量。
接下来n行,每行是一个学生的信息。学生信息分为两部分,先是姓名,姓名由字母组成,没有空格。然后是个整数,表示分数。姓名和分数之间用一个空格隔开。
所有学生分数都不相同。姓名长度不超过100字符,分数范围从0到100。
【输出】
对每组输入数据,按分数从低到高输出学生姓名,每个姓名占一行。每组数据的最后输出一行“
**"。
【样例输入】
2
3
Tom 27
Jack 32
Jone 18
2
Will 91
Jane 97
【样例输出】
Jone
Tom
Jack


Will
Jane
****(10分)
我的答案:
#include
#include
#include
#include
using namespace std;

typedef struct student{
string name;
int score;
}student;

bool comparison(student a,student b){
return a.score<b.score;
}

int main(){
int t,n;
cin>>t;
while(t–){
cin>>n;
vectorarray(n);
for(int i=0;i<n;i++){
cin>>array[i].name>>array[i].score;
}
sort(array.begin(),array.end(),comparison);
for(int i=0;i<n;i++){
cout<<array[i].name<<endl;
}
cout<<“"<<endl;
}
return 0;
}
/

题目得分
参考答案:
#include
#include
#include
#include
using namespace std;
// 此处填写你的代码
class Student {
public:
string name;
int score;
};
bool operator<(const Student &s1, const Student &s2) {
return s1.score < s2.score;
}
istream &operator>>(istream &i, Student &s) {
i >> s.name >> s.score;
return i;
}
ostream &operator<<(ostream &o,const Student &s) {
o << s.name;
return o;
}
// 填写代码结束
int main() {
int t;
vector v;
cin >> t;
while(t–) {
int n;
cin >> n;
Student st;
v.clear();
for( int i = 0;i < n; ++i ) {
cin >> st;
v.push_back(st);
}
sort(v.begin(),v.end());
for( int i = 0;i < v.size(); ++ i)
cout << v[i] << endl;
cout << "
*” << endl;
}
return 0;
}
【描述】
某个科室的病房分为重症和普通,只有当病人的疾病严重程度超过了入住重症病房的最低严重值,才可以安排入住重症病房。
现在要求设计一个程序,给病人安排好病房。疾病的严重程度用0到10来表示,0表示小毛病,10表示非常严重。
【输入】
第一行输入病人的个数m(m < 50),以及安排住入重症病房的最低严重值a。
紧接着m行,每行表示病人编号(三位,用0补齐)及其疾病的严重程度(浮点数,1位小数)。
【输出】
每个病人的疾病严重程度都不一样。输出要求按照病人的严重程度输出住在重症病房里的病人的编号。
【注意】
如果当前所有病人的严重程度并不满足住在重症病房里,则输出“None.”。
【输入示例】
10 7.55
006 6.5
005 8.0
004 3.5
009 8.5
011 7.0
043 9.5
003 5.0
103 6.0
112 4.0
118 9.0
【输出示例】
043 9.5
118 9.0
009 8.5
005 8.0
【提示】
可以定义如下结构类型:
struct Person {
int no; // 病人的编号
double num; // 病人病情严重程度
};(10分)
我的答案:
#include
bool comparison(Person a,Person b){
return a.num>b.num;
}
int main(){
int j=0,n,bh;
double min,cd;
cin>>n>>min;
Person person[n];
for(int i=0;i<n;i++){
cin>>bh>>cd;
if(cd>min){
person[j].no=bh;
person[j].num=cd;
j++;
}
}
sort(person,person+j,comparison);
if(j!=0){
for(int i=0;i<j;i++){
cout<<setw(3)<<setfill(‘0’)<<person[i].no<<" ";
cout<<fixed<<setprecision(1)<<person[i].num<<endl;
}
}
else{
cout<<“None.”;
}
}
题目得分
参考答案:
#include
#include
using namespace std;
struct Person {
int no; // 病人的编号
double num; // 病人病情严重程度
};
int main() {
Person p[55]; // 表示重症病人的结构数组
int m; // m个病人
double a; // 入住重症病房的最低严重值
int n; // 临时变量,表示当前输入的病人的编号
double t; // 临时变量,表示当前输入的病人的严重值
int len = 0; // 表示当前已经遇到的重症病人的人数
Person temp;
cin >> m >> a;
for(int i = 0; i < m; ++i) { // 读入m个人的信息并确定是否重症病人
cin >> n >> t; // 读入病人的编号和严重值
if(t > a) {
p[len].no=n;
p[len].num=t;
len++;
}
}
if(len==0) { // 假如没有重症病人
cout << “None.” << endl;
return 0;
}
int flag;
for(int i = 1; i < len; ++i) { // 对重症病人按严重值排序 ,冒泡算法
flag = 1;
for(int j = 0; j < len - i; ++j) {
if(p[j].num < p[j+1].num) {
flag = 0;
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
if(flag)
break;
}
for(int i = 0; i < len; ++i) // 按重症病人的严重值由大到小输出他们的信息。
cout << setw(3) << setfill( ‘0’) << p[i].no << " "
<< fixed << setprecision(1) << p[i].num << endl;
return 0;
}
【描述】
对一个整数n,如果其各个位数的数字相加得到的数m能整除n,则称n为自整除数。例如21,21%(2+1)0,所以21是自整除数。现求出从10到n(n<100)之间的所有自整除数。
【输入】
输入一个整数n(10≤n<100)。
【输出】
按从小到大的顺序输出所有大于等于10、小于等于n的自整除数,每行一个自整除数。
【输入示例】
47
【输出示例】
10
12
18
20
21
24
27
30
36
40
42
45(10分)
我的答案:
#include
using namespace std;
int main(){
int n;
cin>>n;
for(int i=10;i<=n;i++){
int j=i,c=0;
while(j!=0){
c+=(j%10);
j=j/10;
}
if(i%c
0){
cout<<i<<endl;
}
}

return 0;

}
题目得分
参考答案:
#include
using namespace std;
int main() {
int n;
cin >> n;
for(int i = 10; i <= n; i++){
int temp = i;
int sum = 0;
while(temp != 0) {
sum += temp % 10;
temp /= 10;
}
if(i % sum == 0)
cout << i << endl;
}
return 0;
}
【描述】
将输入的学生信息输出。
【输入】
第一行是整数t,表明数据组数。
在每组数据中:
第一行先是整数n(n<100),表示有n个学生。
接下来有n行,每行表示一个学生。先是一个无空格的字符串,表示姓名,然后是一个非负整数,表示学号。中间用单个空格隔开。
姓名长度不超过100字符,学号小于1000。
【输出】
按照输入的顺序,输出每个学生的信息。先输出学号,再输出姓名,中间用单个空格隔开。
一组数据处理完后,要输出一行 “****”。
【样例输入】
2
3
Tom 12
Jack 20
Marry 89
2
Jade 78
White 76
【样例输出】
12 Tom
20 Jack
89 Marry


78 Jade
76 White
(10分)
我的答案:
class Student{
private:
string name;
int id;
public:
Student(){
name="";
id=0;
}
Student(string Name,int Id){
name=Name;
id=Id;
}
void Read(){
string Name;
int Id;
cin>>Name>>Id;
name=Name;
id=Id;
}
void Print(){
cout<<id<<" "<<name<<endl;
}
};
题目得分
参考答案:
#include
#include
using namespace std;
// 此处填写你的代码
class Student {
private:
string name;
int num;
public:
void Read() {
cin >> name >> num;
}
void Print() {
cout << num << " " << name << endl;
}
Student() { }
Student(string s, int n):name(s), num(n) { }
};
// 填写代码结束
int main() {
int t;
cin >> t;
Student s(“Tom”, 12);
while(t–) {
int n;
cin >> n;
Student st;
for(int i = 0; i < n; ++i) {
st.Read();
st.Print();
}
cout << "
" << endl;
}
return 0;
}
【描述】
小明是一个熊孩子,他很想知道某一个日期是星期几。他知道你正在学习C++,所以想请你写一个程序,实现一个Date类。Date类的定义如下:

class Date {
public:
Date(int year, int month, int day);
int getWeekday() const;
private:
int year;
int month;
int day;
};
成员变量year、month、day分别代表年月日。现在你要实现Date函数和getWeekday函数,并编写main函数。getWeekday函数,如果日期合法,返回1~7中某个数值,表示星期一到星期天中某一天(其中1为星期一),如果日期不合法,则返回-1。
【输入】
输入包含多组数据。每行包括三个整数year(2000≤y≤9999)、month、day。输入数据以0 0 0结束。
【输出】
每组数据输出一行,每行包括一个整数。1表示星期一,7表示星期日,等等,若数据非法,则输出-1。
0 0 0不需输出
【输入示例】
2013 2 26
2013 2 29
0 0 0
【输出示例】
2
-1
【提示】2000年1月1日是星期六。
求星期几:(6 + 2000年1月1日至输入日期的天数 - 1)% 7 + 1
(10分)
我的答案:
#include
class Date {
public:
Date(int year, int month, int day);
int getWeekday() const;
private:
int year;
int month;
int day;
};
Date::Date(int year, int month, int day){
this->year=year;
this->month=month;
this->day=day;
}
int Date::getWeekday() const{
int a[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int b[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
int all=0;
if(year0&&month0&&day0)
exit(0);
else{
for(int i=2000;i<year;i++){
if((i%4
0&&i%100!=0)||(i%4000)){
all+=366;
}
else{
all+=365;
}
}
if((year%4
0&&year%100!=0)||(year%4000)){
for(int i=1;i<month;i++){
all+=b[i];
if(i
month-1)
if(day>b[i+1])
return -1;
}
}
else{
for(int i=1;i<month;i++){
all+=a[i];
if(imonth-1)
if(day>a[i+1])
return -1;
}
}
all+=day;
}
all= (6+all-2)%7+1;
return all;
}
题目得分
参考答案:
#include
using namespace std;
class Date {
public:
Date(int year, int month, int day);
int getWeekday() const;
private:
int year;
int month;
int day;
};
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
Date::Date(int year, int month, int day) {
this->year = year;
this->month = month;
this->day = day;
}
int Date::getWeekday() const {
const int DAYS_PER_MONTH[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
if(year < 2000 || year > 9999)
return -1;
if(month < 1 || month > 12)
return -1;
if(day < 1 || day > DAYS_PER_MONTH[month])
return -1;
int sum = 0;
// 处理年
for(int i = 2000; i < year; ++i) {
if(isLeapYear(i))
sum += 366;
else
sum += 365;
}
// 处理月
for(int i = 1; i < month; ++i)
sum += DAYS_PER_MONTH[i];
if(isLeapYear(year))
if(month > 2 || month == 2)
sum += 1;
// 处理日
sum += day - 1; // 除去2000年1月1日
return (6 + sum - 1) % 7 + 1;
}
int main() {
int year, month, day;
while(cin >> year >> month >> day) {
if(year == 0 && month == 0 && day == 0)
break;
Date d(year, month, day);
cout << d.getWeekday() << endl;
}
return 0;
}
【描述】
有两个字符串str和substr,str的字符个数不超过10,substr的字符个数为3。将substr插入到str中ASCII码最大的那个字符后面,若有多个最大则只考虑第一个。
【输入】
输入包括若干行,每一行为一组测试数据,格式为
str substr
【输出】
对于每一组测试数据,输出插入之后的字符串。
【输入示例】
abcab eee
12343 555
【输出示例】
abceeeab
12345553(10分)
我的答案:
#include
#include
using namespace std;
int main(){
string s;
while(cin>>s){
string sub,n="";
char c;
cin>>sub;
int i;
for(i=0;i<s.length();i++){
if(i
0)
c=s[i];
if(s[i]>c)
c=s[i];
}
for(i=0;i<s.length();i++){
if(c==s[i]){
int t=s.length()-1;
n.append(s.substr(0,i+1));
n.append(sub);
n.append(s.substr((i+1),t));
}
}
cout<<n<<endl;
}

}
题目得分
参考答案:
#include
#include
using namespace std;
int main(){
string str, substr;
// 处理多组数据
while(cin >> str) {
cin >> substr;
// 用len遍历str,获得长度、最大ASCII字符及其下标
int len = 0;
char maxChar = 0;
int maxIdx = 0;
// 遍历数组,并获得相关信息
len = str.length();
for(int i = 0; i < len; ++i) {
if(str[i] > maxChar) {
maxChar = str[i];
maxIdx = i;
}
}
str.insert(maxIdx + 1, substr);
cout << str << endl;
}
return 0;
}
【描述】
下面是一个图书的单价表:
《计算概论》28.9元/本、《数据结构与算法》32.7元/本、《数字逻辑》45.6元/本、《C++程序设计教程》78元/本、《人工智能》35元/本、《计算机体系结构》86.2元/本、《编译原理》27.8元/本、《操作系统》43元/本、《计算机网络》56元/本、《Java程序设计》65元/本。
给定每种图书购买的数量,计算应付的总费用。
【输入】
第一行包含一个正整数n(0 < n <100),表示有n组测试数据;接下来n行,每行包含一组测试数据。每组测试数据包含10个整数(大于等于0、小于等于100),分别表示购买的《计算概论》、《数据结构与算法》、《数字逻辑》、《C++程序设计教程》、《人工智能》、《计算机体系结构》、《编译原理》、《操作系统》、《计算机网络》、《Java程序设计》的数量(以本为单位),整数以用空格间隔。
【输出】
对于每组测试数据,输出一行,表示应付的总费用,结果保留2位小数。
【输入示例】
2
1 5 8 10 5 1 1 2 3 4
3 5 6 3 100 1 1 0 1 0
【输出示例】
2140.20
4427.80
(10分)
我的答案:
#include
#include
using namespace std;
int main(){
int n,a[10];
cin>>n;
while(n–){
double total;
for(int i=0;i<10;i++){
cin>>a[i];
}
total=a[0]*28.9+a[1]*32.7+a[2]*45.6+a[3]*78+a[4]*35+a[5]*86.2+a[6]*27.8+a[7]*43+a[8]*56+a[9]*65;
cout<<fixed<<setprecision(2)<<total<<endl;
}

return 0;

}
题目得分
参考答案:
#include
#include
using namespace std;
int main() {
double prices[10] = {28.9, 32.7, 45.6, 78, 35, 86.2, 27.8, 43, 56, 65};
int n;
cin >> n;
for(int i = 0; i < n; ++i) {
double sum = 0, count;
for(int i = 0; i < 10; ++i) {
cin >> count;
sum += count * prices[i];
}
cout << fixed << setprecision(2) << sum << endl;
}
return 0;
}
【描述】
用手机发短信,一般一条短信资费为0.1元,但限定每条短信的内容在70个字以内(包括70个字)。如果你所发送的一条短信超过了70个字,则大多数手机会按照每70个字一条短信的限制把它分割成多条短信发送。假设已经知道你当月所发送的每条短信的字数,试统计一下你当月短信的总资费。
【输入】
第一行是整数n,表示当月短信总条数,其余n行每行一个整数,表示各条短信的字数。
【输出】
当月短信总资费,单位为元,结果保留1位小数。
【输入示例】
10
39
49
42
61
44
147
42
72
35
46
【输出示例】
1.3(10分)
我的答案:
#include
#include
using namespace std;
int main(){
int c=0,a,n;
cin>>n;
while(n–){
cin>>a;
while(a>70){
a=a-70;
c++;
}
c++;
}
cout<<c*0.1<<endl;
return 0;
}
题目得分
参考答案:
#include
#include
#include
using namespace std;
int main() {
int n;
cin >> n;
double sum = 0;
for(int i = 0; i < n; ++i) {
int word;
cin >> word;
if (word <= 70)
sum += 0.1;
else
sum += ceil(1.0 * word / 70) * 0.1;
}
cout << fixed << setprecision(1) << sum << endl;
return 0;
}

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值