C++ OJ基础

C++ OJ基础

在学校学习C++程序设计基础课程的OJ题目 缺少第二十题

习题练习(一)打印图形

Problem Description

拟用setw、cout和for循环编写程序,打印输出“输出样例”中的图形。请完善下面的程序:

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{  
  int n;  
  //你的代码将被嵌在这里    
  return 0;
}

Input Description

从键盘录入一个正整数n,用于表示输出图形的行数

Output Description

按格式输出n行星号图形

Sample Input

4

Sample Output

   *
  ***
 *****
*******

解题代码

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{  
  	int n; 	
	cin >> n;
	for(int i = 0;i < n;i++)
	{
		cout << setw(n-i);
		for(int j = 1;j <= 2 * i + 1;j++)
		{
			cout << "*";
		}
		if(i +1 < n)cout << endl;
	}
  return 0;
}

运行结果
在这里插入图片描述

习题练习(二)数据的输入输出

Problem Description

某高校教师的课酬计算方法是:教授100元/小时,副教授80元/小时,讲师60元/小时,助教40元/小时。编写计算教师课酬的程序,从键盘输入教师的姓名、职称、授课时数,然后输出该教师应得的课酬。

请完善下面的程序:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    const int js=100,fjs=80,jshi=60,zj=40;
    string name;
    string title;
    int hour;
    double wage;
    cout<<"please input name,title(js,fjs,jshi,zj),hour:"<<endl;
    //你的代码将被嵌在这里 
    return 0;
}

Input Description

Lili fjs 90

Sample Output

please input name,title(js,fjs,jshi,zj),hour:
the wage is :7200

解题代码

#include <iostream>
#include <string>
using namespace std;
int main()
{
    const int js=100,fjs=80,jshi=60,zj=40;
    string name;
    string title;
    int hour;
    double wage;
    cout<<"please input name,title(js,fjs,jshi,zj),hour:"<<endl;
	cin >> name >> title >> hour;
	if(title == "js") 
	{
		wage = hour * js;
	}
	else if(title == "fjs") 
	{
		wage = hour * fjs;
	}
	else if(title == "jshi") 
	{
		wage = hour * jshi;
	}
	else if(title == "zj") 
	{
		wage = hour * zj;
	}
	cout << "the wage is :" << wage;
     return 0;
}

运行结果
在这里插入图片描述

习题练习(三)函数重载

Problem Description

编写重载函数min(),分别计算int、double、float、long类型数组中的最小值。
程序如下,请完善该程序的设计:

#include <iostream>
using namespace std;
int min(int [],int);
double min(double[],int);
float min(float[],int);
long min(long[],int);
int main(){
         int a[6]={2,22,0,-6,67,-111};
         int aa[4]={5,19,2,28};
         double b[8]={2.2,62,-6.1,500,68.2,-500.345,-8,1000};
         float c[4]={3.2,-8.61,699,33};
         long d[3]={3265891,14789,-63256};
         cout<<"the least number in a[6] is "<<min(a,6)<<endl;
         cout<<"the least number in b[8] is "<<min(b,8)<<endl;
         cout<<"the least number in c[4] is "<<min(c,4)<<endl;
         cout<<"the least number in d[3] is "<<min(d,3)<<endl;
         cout<<"the least number in aa[4] is "<<min(aa,4)<<endl;
         return 0;
}
//你的代码将被嵌在这里

Sample Output

the least number in a[6] is -111
the least number in b[8] is -500.345
the least number in c[4] is -8.61
the least number in d[3] is -63256
the least number in aa[4] is 2

解题代码

#include <iostream>
using namespace std;
int min(int [],int);
double min(double[],int);
float min(float[],int);
long min(long[],int);
int main(){
         int a[6]={2,22,0,-6,67,-111};
         int aa[4]={5,19,2,28};
         double b[8]={2.2,62,-6.1,500,68.2,-500.345,-8,1000};
         float c[4]={3.2,-8.61,699,33};
         long d[3]={3265891,14789,-63256};
         cout<<"the least number in a[6] is "<<min(a,6)<<endl;
         cout<<"the least number in b[8] is "<<min(b,8)<<endl;
         cout<<"the least number in c[4] is "<<min(c,4)<<endl;
         cout<<"the least number in d[3] is "<<min(d,3)<<endl;
         cout<<"the least number in aa[4] is "<<min(aa,4)<<endl;
         return 0;
}
//你的代码将被嵌在这里
int min(int arr[],int n)
{
   int min = arr[0];
   for(int i = 1;i < n;i++)
      if(min > arr[i]) min = arr[i];
   return min;
}

double min(double arr[],int n)
{
   double min = arr[0];
   for(int i = 1;i < n;i++)
      if(min > arr[i]) min = arr[i];
   return min;
}

float min(float arr[],int n)
{
   float min = arr[0];
   for(int i = 1;i < n;i++)
      if(min > arr[i]) min = arr[i];
   return min;
}

long min(long arr[],int n)
{
   long min = arr[0];
   for(int i = 1;i < n;i++)
      if(min > arr[i]) min = arr[i];
   return min;
}

习题练习(四)设计矩形类

Problem Description

定义并实现一个矩形类,有长、宽两个属性,由成员函数area计算矩形的面积。

下面的程序不完整,请完善它:

#include <iostream>
using namespace std;
class rectangle{
//你的代码将被嵌在这里
};
int main()
{
    rectangle r(3,4);
    cout<<r.area();
    return 0;
}

Sample Output

12

解题代码

#include <iostream>
using namespace std;
class rectangle{
//你的代码将被嵌在这里
int len,wid;
public:
    rectangle(int len,int wid){this->len = len;this->wid = wid;}
    int area(){return this->len * this->wid;}
};
int main()
{
    rectangle r(3,4);
    cout<<r.area();
    return 0;
}

习题练习(五)定义Tree类

Problem Description

定义一个Tree(树)类,有成员ages(树龄),成员函数grow(int years)对ages加上years, age()显示Tree对象的ages的值。

下面的程序不完整,请编程完善:

#include <iostream>
using namespace std;
class Tree{
//你的代码将被嵌在这里
};
int main()
{
    Tree t;
    t.setages(3);
    t.age();
    t.grow(20);
    t.age();
    return 0;
}

Sample Output

3
23

解题代码

#include <iostream>
using namespace std;
class Tree{
//你的代码将被嵌在这里
int ages;
public:
    void setages(int age){this->ages = age;}
    void age(){cout << this->ages << endl;};
    void grow(int years){this->ages += years;}
    };
int main()
{
    Tree t;
    t.setages(3);
    t.age();
    t.grow(20);
    t.age();
    return 0;
}

习题练习(六)完善职工工资类Salary的设计

Problem Description

某单位的职工工资包括基本工资Wage,岗位工资Subsidy,房租Rent,水费WaterFee,电费ElecFee。设计实现工资管理的类Salary,该类的形式如下:

class Salary{
private:double Wage,Subsidy,Rent,WaterFee,ElecFee;
public:
    Salary(……){初始化工资数据的各项};
    Salary(){初始化工资的各分项数据为0}void setXX(double f){xx=f;};
    double getXX(){return xx;};
    double RealSalary();//计算实发工资
……};
成员函数setXX()用于设置工资的各分项数据,成员函数getXX()用于获取工资的各分项数据,XX代表Wage,Subsidy等数据成员,如Wage对应的成员函数则为setWage()getWage()。
实发工资=Wage+Subsidy-Rent-WaterFee-ElecFee
程序如下,请完成类Salary的设计。程序如下:
#include <iostream>
using namespace std;
class Salary{
private:
    double Wage,Subsidy,Rent,WaterFee,ElecFee;
public:
    Salary(double i1,double i2=0,double i3=0,double i4=0,double i5=0){//以实际参数初始化工资数据的各分项
        Wage=i1;        Subsidy=i2;        Rent=i3;        WaterFee=i4;        ElecFee=i5;
    }
    Salary(){//初始化工资的各分项数据为0
        Wage=Subsidy=Rent=WaterFee=ElecFee=0;
    }
    void setWage(double f);
    double getWage();
    void setSubsidy(double f){Subsidy=f;}
    double getSubsidy(){return Subsidy;}
    void setRent(double f);
    double getRent();
    void setWaterFee(double f){WaterFee=f;}
    double getWaterFee(){return WaterFee;}
    void setElecFee(double f){ElecFee=f;}
    double getElecFee(){return ElecFee;}
    double RealSalary();//计算实发工资         
    void display(){//显示信息
        cout<<"Wage="<<Wage<<"\t\tSubsidy="<<Subsidy<<endl;
        cout<<"Rent="<<Rent<<"\t\tWaterFee="<<WaterFee<<"\t\tElecFee="<<ElecFee<<endl;
        cout<<"实发工资为:"<<RealSalary()<<endl<<endl;
        }
};
//你的代码将被嵌在这里
int main()
{     
    Salary s1(1000,800,200,30,50);
    Salary s2;
    s2.setWage(3000);
    s2.setRent(100);
    cout<<"s1:"<<endl;
    s1.display();
    cout<<"s2:"<<endl;
    s2.display();
    return 0;
}

Sample Output

s1:
Wage=1000		Subsidy=800
Rent=200		WaterFee=30		ElecFee=50
实发工资为:1520

s2:
Wage=3000		Subsidy=0
Rent=100		WaterFee=0		ElecFee=0
实发工资为:2900

解题代码

void Salary::setWage(double f){Wage = f;};
void Salary::setRent(double f){Rent = f;}
double Salary::RealSalary(){return Wage + Subsidy  - Rent - WaterFee - ElecFee;}

习题练习(七)设计矩形类rectangle

Problem Description

定义并实现一个矩形类rectangle,有长(length)、宽(wide)两个属性,成员函数area计算矩形的面积,成员函数setxx和getxx设置和获取length或者wide的值,成员函数display输出矩形的信息(长,宽,面积),要求定义构造函数、拷贝构造函数、赋值运算符函数,能使用对象数组。

//你的代码将被嵌在这里
int main()
{
    rectangle r1(3,4);     //定义一个矩形r1,长为3,宽为4
    r1.display();     //输出矩形r1的有关信息
    rectangle r2;     //定义一个矩形r2
    r2=r1;
    r2.display();     //输出矩形r2的有关信息
    r2.setlength(10);     //把矩形r2的长length改为10
    r2.setwide(20);     //把矩形r2的宽wide改为20
    r2.display();     //再输出矩形r2的有关信息
    rectangle r3(r1);
    r3.display();     //输出矩形r3的有关信息
    rectangle r4[2];     //定义矩形数组r4
    for(int i=0;i<2;i++)     //输出矩形数组r4中各个矩形的信息
           r4[i].display();
    return 0;
}

Sample Output

message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=10 wide=20 area=200
message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=0 wide=0 area=0
message of the rectangle:length=0 wide=0 area=0

解题代码

#include <iostream>
using namespace std;
class rectangle{
    int length,wide;
public:
    rectangle():length(0),wide(0){}
    rectangle(int len,int wid){length = len;wide = wid;}
    rectangle(const rectangle &p)
    {
        if(this == &p)return;
        length = p.length;
        wide = p.wide;
    }
    rectangle & operator=(const rectangle &p)
    {
        if(this == &p) return *this;
        length = p.length;
        wide = p.wide;
        return *this;
    }
    void setlength(int len){length = len;}
    int getlength(){return length;}
    void setwide(int wid){wide = wid;}
    int getwide(){return wide;}
    int area(){return length * wide;}
    void display() {cout << "message of the rectangle:length=" << length << " wide="<< wide << " area=" << area()<<endl;}
};

习题练习(八)设计工人类Worker

Problem Description

设计工人类Worker,它具有姓名name,年龄age,工作部门Dept,工资salary等数据成员。其中,salary为Salary类型的数据,下面的程序拟完成Worker类的设计并用静态成员统计工人的人数,请把程序补充完整。

提示:这里成员函数setXX()用于设置各分项数据,成员函数getXX()用于获取各分项数据,XX代表数据成员,如age对应的成员函数则为setAge()和getAge()。

#include <iostream>
#include <string>
using namespace std;
class Salary{
private:
         double Wage,Subsidy,Rent,WaterFee,ElecFee;//基本工资Wage,岗位工资Subsidy,房租Rent,水费WaterFee,电费ElecFee
public:
         Salary(double i1,double i2=0,double i3=0,double i4=0,double i5=0){//初始化工资数据的各分项
                   Wage=i1;
                   Subsidy=i2;
                   Rent=i3;
                   WaterFee=i4;
                   ElecFee=i5;
         }
         Salary(){//初始化工资的各分项数据为0
                   Wage=Subsidy=Rent=WaterFee=ElecFee=0;}
         void setWage(double f){Wage=f;}
         double getWage(){return Wage;}
         void setSubsidy(double f){Subsidy=f;}
         double getSubsidy(){return Subsidy;}
         void setRent(double f){Rent=f;}
         double getRent(){return Rent;}
         void setWaterFee(double f){WaterFee=f;}
         double getWaterFee(){return WaterFee;}
         void setElecFee(double f){ElecFee=f;}
         double getElecFee(){return ElecFee;}
         double RealSalary(){//计算实发工资,实发工资=Wage+Subsidy-Rent-WaterFee-ElecFee
                   return Wage+Subsidy-Rent-WaterFee-ElecFee;}
};
//你的代码将被嵌在这里
int main(){
         Worker w1("John",30,"design");
         Worker w2;
         cout<<"the total num is: "<<w1.getNum()<<endl;
         w2.setName("Linda");
         cout<<"in w2 the name is: "<<w2.getName()<<endl;
         return 0;
}

Sample Output

the total num is: 2
in w2 the name is: Linda

解题代码

class Worker{
    static int num;
    string name,Dept;
    int age;
    Salary *salary = new Salary();
public:
	Worker():age(0),name(""),Dept(""){Worker::num++;}
	Worker(string n,int i,string dept):age(i),name(n),Dept(dept){Worker::num++;}
	~Worker(){Worker::num--;}
	void setAge(int i) {age = i;}
	int getAge() {return age;}
	void setName(string n) {name = n;}
	string getName() {return name;}
	void setDept(string dept) {Dept = dept;}
	string getDept() {return Dept;}
	void setSalary(double wage) {salary->setWage(wage);}
	Salary * getSalary() {return salary;}
	static int getNum(){return Worker::num;}
};
int Worker::num = 0;

习题练习(九)定义哺乳动物类Mammal和Dog类

Problem Description

定义哺乳动物类Mammal,再由此派生出狗类Dog,定义一个Dog类的对象

//你的程序将被嵌在这里
int main()
{    
    Dog d;
    d.setAge(4);
    d.setWeight(12);
    d.setColor("Black");
    cout<<d.getAge()<<endl;
    cout<<d.getWeight()<<endl;
    cout<<d.getColor()<<endl;
    d.speak();
    return 0;
}

Sample Output

Constructor in Mammal.
Constructor in Dog.
4
12
Black
Dog sound wang,wang,wang!
Destructor in Dog.
Destructor in Mammal.

Hint

1、类Mammal有数据成员Age(年龄,int类型)、Weight(体重,double类型),和对应的set函数以及get函数。
2、Dog定义了新的数据成员Color(颜色,string类型)。
3、Mammal类和Dog类都有成员函数speak。

解题代码

#include <iostream>
#include <string>
using namespace std;
class Mammal{
    int age;
    double weight;
public:
    Mammal(){cout << "Constructor in Mammal.\n";}
    ~Mammal(){cout << "Destructor in Mammal.\n";}
    void setAge(int Age) {age = Age;}
    void setWeight(int Weight) {weight = Weight;}
    int getAge(){return age;}
    double getWeight(){return weight;}
};
class Dog:public Mammal{
    string color;
public:
    Dog(){cout << "Constructor in Dog.\n";}
    ~Dog(){cout << "Destructor in Dog.\n";}
    void setColor(string Color){color = Color;}
    string getColor(){return color;}
    void speak(){cout << "Dog sound wang,wang,wang!\n";}
};

习题练习(十)设计管理出版物的类

Problem Description

某出版社发行图书和光盘,利用继承设计管理出版物的类。

要求如下:建立一个基类Publication存储出版物的标题title、出版物名称name、单价price及出版日期date;用Book和CD类分别管理图书和光盘,它们都从Publication类派生;Book类具有保存图书页数的数据成员page,CD类具有保存播放时间的数据成员playtime;每个类都有构造函数、析构函数,且都有用于从键盘获取数据的成员函数inputData()和用于显示数据的成员函数display()。

请完成下面的程序:

#include<iostream>
#include<string>
using namespace std;
struct Date{//年月日
    int year;
    int month;
    int day;
    Date(int y=0,int m=0,int d=0){year=y;month=m;day=d;}
    ~Date(){}
};
struct Time{//时分秒
    int hour;
    int minute;
    int second;
    Time(int h=0,int m=0,int s=0){hour=h;minute=m;second=s;}
    ~Time(){}
};
class Publication{
private:
    string title;//出版物的标题title
    string name;//出版物的名称name
    float price;//出版物的单价price
    Date date; //出版日期date
public:
    Publication(string t="",string n="",float p=0,int h=0,int m=0,int s=0):date(h,m,s){
        title=t;name=n;price=p;}
    ~Publication(){}
    void inputdata(){        
        cin>>title;        
        cin>>name;        
        cin>>price;        
        cin>>date.year>>date.month>>date.day;
        }
    void display(){
        cout<<"*****display*****"<<endl;
        cout<<"title:"<<title<<endl;
        cout<<"name:"<<name<<endl;
        cout<<"price:"<<price<<endl;
        cout<<"year-month-day:"<<date.year<<"-"<<date.month<<"-"<<date.day<<endl;
        }
};
//你的代码将被嵌在这里
int main()
{
    Book b;
    CD c(1,2,3,"郎朗","肖邦钢琴协奏曲",61,2018,8,1);
    b.inputdata();
    b.display();
    c.display();    
    return 0;
}

Input Description

文学作品
西游记
28
2018 1 8
280

Sample Output

*****display*****
title:文学作品
name:西游记
price:28
year-month-day:2018-1-8
pages:280
*****display*****
title:郎朗
name:肖邦钢琴协奏曲
price:61
year-month-day:2018-8-1
playtime(h:m:s) 1:2:3

解题代码

class Book:public Publication{
    int page;
public:
    Book(){}
    void inputdata()
    {
        Publication::inputdata();
        cin >> page;
    }
    void display()
    {
        Publication::display();
        cout <<"pages:" << page <<endl;
    }
};

class CD:public Publication{
    Time playtime;
public:
    CD(int hour,int minute,int second,string title,string name,float price,int year,int month,int day):Publication(title,name,price,year,month,day),playtime(hour,minute,second){}
    void display()
    {
        Publication::display();
        cout <<"playtime(h:m:s) " << playtime.hour << ":" << playtime.minute << ":" << playtime.second << endl;
    }
};

习题练习(十一)完成学生类和教师类的设计

Problem Description

一个教学系统至少有学生和教师两种类型的人员,假设教师的数据有教师编号、姓名、年龄、性别、职称和系别,学生的数据有学号、姓名、年龄、性别、班级和语文、数学、英语三门课程的成绩。现编程完成学生和教师档案数据的输入和显示。要求如下:

设计三个类Person、Teacher、Student,Person是Teacher和Student的基类,具有此二类共有的数据成员姓名、年龄、性别,并具有输入和显示这些数据的成员函数;Teacher类继承了Person类的功能,并增加对教师编号、职称和系别等数据成员进行输入和显示的成员函数。Student类按同样的方法设计。

根据题意完成下面的程序:

#include <iostream>

using namespace std;

#include <string>

class Person{

private:

string name;

int age;

string sex;

public:

Person(string ="",int =0,string ="");

void inputname(){cin>>name;}

void printname(){cout<<name<<endl;}

void inputage(){cin>>age;}

void printage(){cout<<age<<endl;}

void inputsex(){cin>>sex;}

void printsex(){cout<<sex<<endl;}

};

Person::Person(string Name,int Age,string Sex){name=Name;age=Age;sex=Sex;}

//你的代码将被嵌入在这里

int main(){
    Teacher t1,t2("张华",33,"男","T001","讲师","计算机系");
    Student s1,s2("李丽",19,"女","S001","0309201",90,92,98);
    t1.inputname();
    t1.inputage();
    s1.inputChinese();
    s1.inputname();
    t1.printname();
    t1.printage();
    s1.printname();
    s1.printage();
    t2.printname();
    t2.printage();
    s2.printname();
    s2.printage();
    return 0;
}

Input Description

John
40
90
Mary

Sample Output

John
40
Mary
0
张华
33
李丽
19

解题代码

class Teacher:public Person{
    string no,title,dept;
public:
    Teacher(){}
    Teacher(string name,int age,string sex,string no,string title,string dept):Person(name,age,sex),no(no),title(title),dept(dept){}
};

class Student:public Person{
    string no,sno;
    double chinese,math,english;
public:
    Student(){}
    Student(string name,int age,string sex,string no,string sno,double chinese,double math,double english):Person(name,age,sex),no(no),sno(sno),chinese(chinese),math(math),english(english){}
    void inputChinese(){cin >> chinese;}
};

习题练习(十二)设计飞机类Plane及其派生类

Problem Description

设计一个飞机Plane类,由它派生出歼击机Fighter类和轰炸机Bomber类,歼击机Fighter类和轰炸机Bomber类又共同派生出歼轰机(多用途战斗机)Fighter_Bomber类。虚基类描述飞机类及其派生的类族。

#include<iostream>
using namespace std;
class Plane    //飞机类
{
private:
    float wing;        //机翼长度
    float body;        //机身长度
    float tail;        //尾翼长度
    float voyage;      //航程
    int guest;         //旅客人数
public:
    Plane(float,float,float,float,int);    
    void display();
};
void Plane::display()
{
    cout<<"Plane:\twing:"<<wing<<" body:"<<body<<" tail:"<<tail<<" voyage:"<<voyage<<" guest:"<<guest;
}
Plane::Plane(float w,float b,float t,float v,int n)
{
    wing=w;
    body=b;
    tail=t;
    voyage=v;
    guest=n;
}
//你的代码将被嵌在这里

int main()
{    
    Fighter f(10.0,6.0,2.5,1800,1,8);             //歼击机
    f.display();
    Bomber b(30,9,6,12000,12,6000);             //轰炸机
    b.display();
    Fighter_Bomber fb(20,7,3.2,4000,2,6,2500);    //歼轰机
    fb.display();   
    return 0;
}

Sample Output

This is a fighter!
Plane:	wing:10 body:6 tail:2.5 voyage:1800 guest:1
missile:8
This is a bomber!
Plane:	wing:30 body:9 tail:6 voyage:12000 guest:12
bomb:6000
This is a fighter_bomber!
This is a fighter!
Plane:	wing:20 body:7 tail:3.2 voyage:4000 guest:2
missile:6
bomb:2500
Fight!
Attack!

Hint

1、Plane类有数据成员:wing(机翼长度),body(机身长度),tail(尾翼长度),voyage(航程),guest(旅客人数);成员函数display,用于显示数据成员的值;
2、Fighter类(歼击机类)有新的数据成员missile(导弹数),重定义了display函数,新定义了fight函数(输出字符串“Fight!”);
3、Bomber类(轰炸机类)有新的数据成员bomb(载弹量),重定义display函数,新定义attack函数(输出字符串“Attack!”)、getbomb函数。
4、Fighter_Bomber类(歼轰机类), 重定义了display函数。
5、Plane类(飞机类)为虚基类。

解题代码

class Fighter:public Plane{
protected:
    int missile;
public:
    Fighter(float w,float b,float t,float v,int n,int Missile):Plane(w,b,t,v,n),missile(Missile){}
    void display()
    {
        cout << "This is a fighter!\n";
        Plane::display();
        cout << "\nmissile:" << missile << endl;
    }
    void fight(){cout << "Fight!\n";}
};

class Bomber:public Plane{
protected:
    int bomb;
public:
    Bomber(float w,float b,float t,float v,int n,int bom):Plane(w,b,t,v,n),bomb(bom){}
    void display()
    {
        cout << "This is a bomber!\n";
        Plane::display();
        cout << "\nbomb:" << bomb << endl;
    }
    void attack(){cout << "Attack!\n";}
};

class Fighter_Bomber:public Fighter,Bomber{
public:
    Fighter_Bomber(float w,float b,float t,float v,int n,int Missile,int bom):Fighter(w,b,t,v,n,Missile),Bomber(w,b,t,v,n,bom){}
    void display()
    {
        cout << "This is a fighter_bomber!\n";
        Fighter::display();
        cout << "bomb:" << bomb << endl;
        Fighter::fight();
        Bomber::attack();
    }
};

习题练习(十三)定义类Shape、Rectangle、Circle和Square

Problem Description

定义一个基类Shape,在此基础上派生出RectangleCircle,两者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。请完善下面的程序。

class Shape{
public:
    virtual float getArea()=0;
    virtual ~Shape(){}
};
//你的代码将被嵌在这里
int main()
{  Shape *ps;
    ps=new Circle(5);
    cout<<"The area of the Circle is "<<ps->getArea()<<endl;
    delete ps;
    Rectangle *pr;
    pr=new Rectangle(5,6);
    cout<<"The area of the Rectagle is "<<pr->getArea()<<endl;
    delete pr;
    Square s(8);
    pr=&s;
    cout<<"The area of the Square is "<<pr->getArea()<<endl;
    delete pr;    
    return 0;
}

Sample Output

The area of the Circle is 78.5
The area of the Rectagle is 30
The area of the Square is 64

Hint

1、在Rectangle类中有长和宽两个数据成员,在Circle类中有一个数据成员即半径。
2、本题圆周率使用3.14

解题代码

// 注意需要导入头文件 后面用到了cout
#include <iostream>
using namespace std;
// 特别注意 父类中的虚函数 在子类中需要有具体的函数体
// 类似于Java中的父类为抽象类 子类必须实现父类中的抽象方法
// 由于父类中定义的getArea()方法的返回值为float 子类中也使用相同的返回值类型float
// 矩形类继承了Shape
class Rectangle:public Shape{
    // 矩形类有长和宽两个属性 
    // class默认的权限级别是private
    int length,wide;
public:
    // 构造器 传入长和宽 直接在初始化列表赋值即可
    Rectangle(int len,int wid):length(len),wide(wid){}
    // 获取矩形的面积的方法 直接返回面积的值  
    // 由于前面的数据类型是int 这里存在 int -> flaot的自动类型提升
    float getArea(){return length * wide;}
};

// 圆形类继承了Shape
class Circle:public Shape{
    // 圆的半径 
    int r;
public:
    // 构造方法 传入半径 直接在初始化列表赋值 
    Circle(int R):r(R){}
    // 获取圆形的面积的方法 直接返回面积值 
    // 题目说明 圆周率为3.14
    float getArea(){return 3.14 * r * r;}
};

// 正方形类继承了矩形类
class Square:public Rectangle{
    // 正方形的边
    int side;
public:
    // 构造方法 传入边长 直接在初始化列表赋值 
    // 由于继承的是矩形类 在构造自己之前会先对父类进行构造 在初始化列表中对父类进行构造
    Square(int Side):Rectangle(Side,Side),side(Side){}
    // 获取正方形面积的方法
    float getArea(){return side * side;}
};

习题练习(十四)用抽象类设计计算二维平面图形面积的程序

Problem Description

用抽象类设计计算二维平面图形面积的程序,在基类TDshape中设计纯虚函数area()和printName()。area()用于计算几何图形的面积,printName()用于打印输出几何图形的类名,如Triangle类的对象就打印输出“Triangle”。每个具体形状的类则从抽象类TDshape派生,各自定义其独有的数据成员和成员函数,并定义area()和printName()的具体实现代码。函数fp和函数fr是以TDshape为接口的函数,借以访问具体类如Triangle和Rectangle类的成员函数area()和printName()。
在这里插入图片描述

//你的代码将被嵌入在这里
void fp(TDshape *p);
void fr(TDshape &r);
int main()
{
    Triangle triangle(3,4);//width为3,height为4
    Rectangle rectangle(4,9);//width为4,height为9
    rectangle.setWidth(10);
    cout<<"******from fp:"<<endl;
    fp(&triangle);
    fp(&rectangle);
    cout<<"******from fr:"<<endl;
    fr(triangle);
    fr(rectangle);
    return 0;
}
void fp(TDshape *p)
{
    cout<<"area:"<<p->area()<<endl;
    p->printName();
}
void fr(TDshape &r)
{
    cout<<"area:"<<r.area()<<endl;
    r.printName();
}

Sample Output

******from fp:
area:6
Triangle
area:90
Rectangle
******from fr:
area:6
Triangle
area:90
Rectangle

解题代码

// 后面的使用到了 cout 需要导入相应的头文件
#include <iostream>
using namespace std;
// 基类
class TDshape{
public:
    // 定义两个虚函数 一个用于计算面积 一个用于打印名称
    virtual double area()=0;
    virtual void printName()=0;
};

// Triangle继承了 TDshape
class Triangle:public TDshape{
    // 三角形的底边长 和 高
    double width,height;
public:
    // 构造方法 传入底边长和高 初始化列表赋值
    Triangle(double wid,double hei):width(wid),height(hei){}
    // 设置底边长和高的值的方法
    void setWidth(double wid){width = wid;}
    void setHeight(double hei){height = hei;}
    // 获取底边长和高的值的方法
    double getWidth(){return width;}
    double getHeight(){return height;}
    // 计算三角形面积的方法 (底边 * 高)/2
    double area(){return (width * height)/2;}
    // 打印图形的名称 根据题目需要打印Triangle 注意换行
    // 也可以写成 void printName(){cout << "Triangle" << endl;}
    void printName(){cout << "Triangle\n";}
};
// Rectangle TDshape
class Rectangle:public TDshape{
    // 矩形的长和宽
    double width,height;
public:
    // 构造方法 传入长和宽 初始化列表赋值
    Rectangle(double wid,double hei):width(wid),height(hei){}
    // 设置长和宽的值的方法
    void setWidth(double wid){width = wid;}
    void setHeight(double hei){height = hei;}
    // 获取长和宽的值的方法
    double getWidth(){return width;}
    double getHeight(){return height;}
    // 计算矩形面积的方法 长 * 宽
    double area(){return width * height;}
    // 打印图形的名称 根据题目需要打印Rectangle 注意换行
    void printName(){cout << "Rectangle\n";}
};

习题练习(十五)用虚函数和虚基类描述飞机类及其派生的类族

Problem Description

设计一个飞机Plane类,由它派生出歼击机Fighter类和轰炸机Bomber类,歼击机Fighter类和轰炸机Bomber类又共同派生出歼轰机(多用途战斗机)Fighter_Bomber类。用虚函数和虚基类描述飞机类及其派生的类族。

#include<iostream>
using namespace std;
class Plane    //飞机类
{
private:
    float wing;        //机翼长度
    float body;        //机身长度
    float tail;        //尾翼长度
    float voyage;      //航程
    int guest;         //旅客人数
public:
    Plane(float w,float b,float t,float v,int n)
{
    wing=w;
    body=b;
    tail=t;
    voyage=v;
    guest=n;
}       
//你的代码将被嵌在这里

int main()
{    
    Plane *p;    
    Fighter f(10.0,6.0,2.5,1800,1,8);             //歼击机    
    Bomber b(30,9,6,12000,12,6000);             //轰炸机    
    Fighter_Bomber fb(20,7,3.2,4000,2,6,2500);    //歼轰机    
    p=&f;
    cout<<"********p=&f"<<endl;
    p->display();
    p=&b;
    cout<<"\n********p=&b"<<endl;
    p->display();
    p=&fb;
    cout<<"\n********p=&fb"<<endl;
    p->display();    
    return 0;
}

Sample Output

********p=&f
This is a fighter!
Plane:	wing:10 body:6 tail:2.5 voyage:1800 guest:1
missile:8

********p=&b
This is a bomber!
Plane:	wing:30 body:9 tail:6 voyage:12000 guest:12
bomb:6000

********p=&fb
This is a fighter_bomber!
This is a fighter!
Plane:	wing:20 body:7 tail:3.2 voyage:4000 guest:2
missile:6
bomb:2500
Fight!
Attack!

Hint

1、Plane类有数据成员:wing(机翼长度),body(机身长度),tail(尾翼长度),voyage(航程),guest(旅客人数);成员函数display,用于显示数据成员的值;
2、Fighter类(歼击机类)有新的数据成员missile(导弹数),重定义了display函数,新定义了fight函数(输出字符串“Fight!”);
3、Bomber类(轰炸机类)有新的数据成员bomb(载弹量),重定义display函数,新定义attack函数(输出字符串“Attack!”)、getbomb函数。
4、Fighter_Bomber类(歼轰机类), 重定义了display函数。
5、Plane类(飞机类)为虚基类。
6、display为虚函数。

解题代码

// 将Plane补充完整
// 定义了一个虚函数 display 输出飞机的基本信息
virtual void display()
	{
        cout<<"Plane:\twing:"<<wing<<" body:"<<body<<" tail:"<<tail<<" voyage:"<<voyage<<" guest:"<<guest;
    }
};

// Fighter 使用虚继承的方式继承Plane
class Fighter:virtual public Plane{
// Fighter类有一个新的成员missile 这个成员是受保护的 可以继承给子类
protected:
    int missile;
public:
    // 构造器 在初始化列表中先初始化Plane 然后再初始化missile
    Fighter(float w,float b,float t,float v,int n,int Missile):Plane(w,b,t,v,n),missile(Missile){}
    // 由于虚继承了Plane类 需要实现display方法 按照题目要求输出指定内容
    void display()
    {
        cout << "This is a fighter!\n";
        // 调用父类的display方法
        Plane::display();
        cout << "\nmissile:" << missile << endl;
    }
    // fight()方法输出自己的类名 注意有换行
    void fight(){cout << "Fight!\n";}
};

// Bomber 使用虚继承的方式继承Plane
class Bomber:virtual public Plane{
// Bomber类有一个新的成员bomb 这个成员是受保护的 可以继承给子类 
protected:
    int bomb;
public:
     // 构造器 在初始化列表中先初始化Plane 然后再初始化bomb
    Bomber(float w,float b,float t,float v,int n,int bom):Plane(w,b,t,v,n),bomb(bom){}
    // 由于虚继承了Plane类 需要实现display方法 按照题目要求输出指定内容
    void display()
    {
        cout << "This is a bomber!\n";
        // 调用了父类的display方法
        Plane::display();
        cout << "\nbomb:" << bomb << endl;
    }
    // attack()方法输出Attack 根据题目要求输出Attack!换行
    void attack(){cout << "Attack!\n";}
};

// Fighter_Bomber类 继承了Fighter Bomber 这里可能出现菱形继承的问题
// 但是前面两个类对于Plane类都是虚继承 可以避免菱形继承
class Fighter_Bomber:public Fighter,Bomber{
public:
    // 构造器 初始化列表中先初始化了Fighter、Bomber、Plane
    Fighter_Bomber(float w,float b,float t,float v,int n,int Missile,int bom):Fighter(w,b,t,v,n,Missile),Bomber(w,b,t,v,n,bom),Plane(w,b,t,v,n){}
    // 需要实现display方法 根据题目要求输出
    void display()
    {
        cout << "This is a fighter_bomber!\n";
        // 调用了Fighter的display()方法
        Fighter::display();
        cout << "bomb:" << bomb << endl;
        // 调用了Fighter类的fight()方法
        Fighter::fight();
        // 调用了Bomber类的attack()方法
        Bomber::attack();
    }
};

习题练习(十六)计算公司员工的工资

Problem Description

某公司有老板Boss、雇员Employee、小时工HourlyWorker和营销人员CommWorker,他们的薪金计算方法如下:

老板实行年薪制,如一年15万;雇员按月计酬,方法是基本工资+奖金;小时工按工作时间计算报酬,方法是工作小时每小时单价;营销人员按月计酬,方法是基本工资+销售利润5%。
每类人员都有姓名、职工编号、年龄、性别、工资等数据。设计计算各类人员报酬的程序,用虚函数getPay()计算各类人员的应得报酬,用虚函数print()打印输出各位工作人员的基本数据。

#include <iostream>
using namespace std;
class Person{
private:
string name;//姓名
string no;//职工编号
int age;//年龄
string sex;//性别
float salary;//工资
public:
Person(string s1,string s2,int Age,string Sex,float Salary=0);
virtual double getPay()=0;
virtual void print();
};
Person::Person(string s1,string s2,int Age,string Sex,float Salary){
name=s1;no=s2;age=Age;sex=Sex;salary=Salary;}
void Person::print(){
cout<<"姓名:"<<name<<"\n职工编号:"<<no<<"\n年龄:"<<age<<"\n性别:"<<sex;}
//你的代码将被嵌在这里
int main(){    
    Boss b("张华","N001",30,"男");
    b.print();
    Employee e("李明","N002",40,"男");
    e.setBWage(900);
    e.setBonus(1000);
    e.print();
    HourlyWorker hw("向力","N003",38,"男");
    hw.settime_Hours(30);
    hw.setUHPrice(60);
    hw.print();
    CommWorker cw("刘晓云","N004",28,"女");
    cw.setBWage(1600);
    cw.setinterest(10000);
    cw.print();
    return 0;
}

Sample Output

********************老板********************
姓名:张华
职工编号:N001
年龄:30
性别:男
年薪:15万元
********************雇员********************
姓名:李明
职工编号:N002
年龄:40
性别:男
基本工资:900
奖金:1000
月薪:1900********************小时工********************
姓名:向力
职工编号:N003
年龄:38
性别:男
每小时单价:60元
工作时间:30小时
报酬:1800********************营销人员********************
姓名:刘晓云
职工编号:N004
年龄:28
性别:女
基本工资:1600元
销售利润:10000元
月酬:2100

Hint

1、将各类人员都有的共有的属性和行为抽象在类Person中,包括姓名、职工编号、年龄、性别等,以及函数getPay()print()2getPay()设计为纯虚函数,将print()设计成一般虚函数,其余类从Person类派生,各类再定义getPay()的实现方法,并重定义函数print()输出具体数据。
3、每个类还需要根据实际情况定义相应的成员函数,获取诸如工作时间、基本工资、销售利润之类的基础数据。

解题代码

// Boss类继承Person类
class Boss:public Person{
public:
    // 构造器 初始化Person
    Boss(string s1,string s2,int Age,string Sex):Person(s1,s2,Age,Sex){}
    // print方法 打印题目指定内容
    void print()
    {
        cout << "********************老板********************\n";
        // 调用父类的print方法
        Person::print();
        cout<< "年薪:15万元" << endl;
    }
    // getPay 获取工资 15万元
    double getPay()
    {
        return 15;
    }
};

// Employee类继承了Person类
class Employee:public Person{
    // Employee类有两个属性 BWage,Bonus 不加权限修饰符默认是private 
    int BWage,Bonus;
public:
    // 构造器 初始化列表初始化父类
    Employee(string s1,string s2,int Age,string Sex):Person(s1,s2,Age,Sex){}
    // 设置 BWage Bonus的方法
    void setBWage(int wage){BWage = wage;};
    void setBonus(int bonus){Bonus = bonus;};
    // 获取工资的方法  工资 = 基本工资+奖金
    double getPay(){return BWage + Bonus;}
    // print()方法打印信息 根据题目要求
    void print()
    {
        cout<<"********************雇员********************\n";
        // 调用父类的print方法
        Person::print();
        cout<< "基本工资:" << BWage << "\n奖金:" << Bonus << "\n月薪;" << getPay() << "元" << endl;
    }
};

// HourlyWorker 继承Person类
class HourlyWorker:public Person{
    // HourlyWorker类有两个属性 time_Hours,UHPrice 不加权限修饰符默认是private
    int time_Hours,UHPrice;
public:
    // 构造器 初始化列表初始化Person
    HourlyWorker(string s1,string s2,int Age,string Sex):Person(s1,s2,Age,Sex){}
    // 设置 time_Hours UHPrice 的方法
    void settime_Hours(int hours){time_Hours = hours;}
    void setUHPrice(int price){UHPrice = price;}
    // 获取工资的方法 小时工工资 = 工作时间(小时) * 每小时工资
    double getPay(){return time_Hours * UHPrice;}
    // print()方法打印信息 根据题目要求
    void print()
    {
        cout << "********************小时工********************\n";
        // 调用父类的print方法
        Person::print();
        cout<< "每小时单价:" << UHPrice << "元\n工作时间:" << time_Hours << "小时\n报酬;" << getPay() << "元" << endl;
    }
};

// CommWorker 继承Person类
class CommWorker:public Person{
    // CommWorker类有两个属性 BWage,interest 不加权限修饰符默认是private
    int BWage,interest;
public:
     // 构造器 初始化列表初始化Person
    CommWorker(string s1,string s2,int Age,string Sex):Person(s1,s2,Age,Sex){}
    // 设置BWage,interest的方法
    void setBWage(int wage){BWage = wage;}
    void setinterest(int Interest){interest = Interest;}
    // 获取工资 营销人员工资 = 基本工资 + 提成(销售利润 * 0.05)
    double getPay(){return (int)(BWage + interest * 0.05);}
    // print()方法打印信息 根据题目要求
    void print()
    {
        cout << "********************营销人员********************\n";
        // 调用父类的print方法
        Person::print();
        cout<< "基本工资:" << BWage << "元\n销售利润:" << interest << "元\n月酬;" << getPay() << "元" << endl;
    }
};

习题练习(十八)实现计数器的前自减、后自减运算

Problem Description

设计一个计算器类Calculator,它只有一个用于计数的数据成员count,该计数器的有效计数范围是0-65535,实现计数器的前自减、后自减运算。

//你的代码将嵌在这里

int main(){    
    Calculator b(200);
    --b;
    b.display();
    b--;
    b.display();   
    return 0;
}

Sample Output

counter number =199
counter number =198

解题代码

// 引入头文件
#include<iostream>
using namespace std;
// 计算器类
class Calculator{
    // 计算数成员
    unsigned int count;
public:
    // 默认构造器
    Calculator(){}
    // 带参构造器
    Calculator(int i){ count = i;}
    // 操作符重载 后缀--
    Calculator operator--()
    {
        count--;
    }
    // 操作符重载 前缀 --
    Calculator operator--(int)
    {
        --count;
    }
    // 打印结果
    void display(){cout << "counter number ="<<count << endl;}
};

习题练习(十九)实现两个计数器相加减的运算

Problem Description

设计一个计算器类Calculator,它只有一个用于计数的数据成员count,该计数器的有效计数范围是0-65535,实现两个计数器相加减的运算。

//你的代码将嵌在这里

int main(){    
    Calculator a(100),b(200),c,d;
    c=a+b;
    c.display();
    d=b-a;
    d.display();
    return 0;
}

Sample Output

counter number =300
counter number =100

解题代码

// 引入头文件
#include<iostream>
using namespace std;
// 计算器类 
class Calculator{
    // 无符号int 0-65535
    unsigned int count;
public:
    // 默认构造器
    Calculator(){}
    // 带参构造器
    Calculator(int i){ count = i;}
    // 操作符重载 +
    Calculator operator+(const Calculator & c)
    {
        Calculator res;
        res.count = count + c.count;
    }
    // 操作符重载 -
    Calculator operator-(const Calculator & c)
    {
        Calculator res;
        res.count = count - c.count;
    }
    // 打印结果
    void display(){cout << "counter number ="<<count << endl;}
};

习题练习(二十一)设计整型链表类List

Problem Description

设计一个整型链表类List,能够实现链表节点的插入(insert)、删除(delete),以及链表数据的输出操作(print)。

提示:链表结点用如下结构定义:
struct Node{//结点的结构
int data;
Node *next;
};

链表类List有一个数据成员head,类型是Node *

根据题目要求完善下面的程序:

#include<iostream>
using namespace std;

struct Node{//结点的结构
    int data;
    Node *next;
};

class List{
private:
    Node* head;
public:

//你的代码将被嵌在这里
int main()
{
    List list;//定义一个空链表list
    list.Listinsert(0,10);//在第0个结点的后面插入值为10的新结点,也即在链表头部插入新的结点
    list.Listinsert(0,66);
    list.Listinsert(1,292);//在第1个结点的后面插入值为10的新结点
    list.Listdelete(66);//删除链表中第一个值为66的结点
    list.Listinsert(2,-2);//在第2个结点的后面插入值为-2的新结点
    list.Listinsert(1,3);//在第1个结点的后面插入值为3的新结点
    list.Listprint();//从头到尾输出链表结点的值,每个输出值占一行
    return 0;
}

Sample Input

Lili fjs 90

Sample Output

292
3
10
-2

解题代码

 	// 构造函数
	List()
    {
        head = NULL;
    }
	// 析构函数
    ~List()
    {
        delete head;
    }
	// 插入方法
    void Listinsert(int i,int value)
    {
        int index = 0;
        // 创建一个节点 
        Node *n = new Node();
        // 组装数据
        n->data = value;
        n->next = NULL;
        
        if(index == i)
        {
            // 如果头节点不为空就头节点替换为插入节点
            if(head != NULL)
            {
              // 将插入节点的下一个节点指向头节点
              n->next = head;
              // 将头节点指向插入节点
              head = n;
            }
            // 如果头节点为空就将头节点指向插入节点
            else
            {
                head = n;
            }
        }
        // 如果不是从头节点插入
        else
        {
            // p用于遍历 q记录前一个节点
            Node *p=NULL,*q=NULL;
            // p指向头节点
            p = head;
            // 遍历查找插入的位置
            while (index != i && p != NULL){q = p;index++; p = p->next;}
            // 找到后将前一个节点的后一个节点指向插入的节点
            q->next = n;
            // 将插入的节点的后一个节点指向当前节点
            n->next = p;
        }
    }
	// 根据值删除节点
    void Listdelete(int value)
    {
        // q用于遍历 p记录前一个节点
        Node *q,*p;
        q = p = NULL;
        // 如果要删除的节点是头节点
        if (head-> data == value)
        {
            // q指向头节点
            q = head;
            // 将头节点指向原来头节点的下一个节点
            head = head->next;
            // 释放原有的头节点的空间
            delete q;
        }else
        // 如果删除的不是头节点
        {
            q = p = head;
     		// 遍历找到要删除的节点
            while(q)
            {
                // p记录前一个节点
                p = q;
                // 找到后退出循环
                if(q->data == value) break;
                q = q->next;
            }
            // 如果q不为空 代表找到了
            if(q != NULL)
            {
                // 将要删除的节点的前一个节点指向要删除节点的下一个节点
                p->next = q->next;
                // 释放掉要删除的节点
                delete q;
            }
            // 找不到 就打印相关信息
            else
            {
                cout << "not found data : " << value<<endl;
            }
        }
    }
	// 打印链表值
    void Listprint()
    {
        Node *q = NULL;
        q = head;
     	// 遍历打印
        while(q != NULL){cout << q->data << endl;q=q->next;}
        // 换行
        cout <<"---------"<<endl;
    }
};

习题练习(二十二)设计矩形类rectangle

Problem Description

定义并实现一个矩形类rectangle,有长(length)、宽(wide)两个属性,成员函数area计算矩形的面积,成员函数setxx和getxx设置和获取length或者wide的值,成员函数display输出矩形的信息(长,宽,面积),要求定义构造函数、拷贝构造函数、赋值运算符函数,能使用对象数组。

//你的代码将被嵌在这里
int main()
{
    rectangle r1(3,4);     //定义一个矩形r1,长为3,宽为4
    r1.display();     //输出矩形r1的有关信息
    rectangle r2;     //定义一个矩形r2
    r2=r1;
    r2.display();     //输出矩形r2的有关信息
    r2.setlength(10);     //把矩形r2的长length改为10
    r2.setwide(20);     //把矩形r2的宽wide改为20
    r2.display();     //再输出矩形r2的有关信息
    rectangle r3(r1);
    r3.display();     //输出矩形r3的有关信息
    rectangle r4[2];     //定义矩形数组r4
    for(int i=0;i<2;i++)     //输出矩形数组r4中各个矩形的信息
           r4[i].display();
    return 0;
}

Sample Output

message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=10 wide=20 area=200
message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=0 wide=0 area=0
message of the rectangle:length=0 wide=0 area=0

解题代码

#include <iostream>
using namespace std;
// rectangle类
class rectangle{
    // 长 宽属性
    int length,wide;
public:
    // 无参构造函数  初始化列表给成员赋值0
    rectangle():length(0),wide(0){}
    // 有参构造函数 初始化列表给成员赋值
    rectangle(int len,int wid){length = len;wide = wid;}
    // 拷贝构造
    rectangle(const rectangle &p)
    {
        if(this == &p)return;
        length = p.length;
        wide = p.wide;
    }
    // 运算符重载 =
    rectangle & operator=(const rectangle &p)
    {
        if(this == &p) return *this;
        length = p.length;
        wide = p.wide;
        return *this;
    }
    // 属性 length wide的set get函数
    void setlength(int len){length = len;}
    int getlength(){return length;}
    void setwide(int wid){wide = wid;}
    int getwide(){return wide;}
    // 计算面积的函数
    int area(){return length * wide;}
    // 打印信息
    void display() {cout << "message of the rectangle:length=" << length << " wide="<< wide << " area=" << area()<<endl;}
};

习题练习(二十三)实现两坐标点的加、减运算

Problem Description

建立一个二维坐标系的类TwoCoor,用x、y表示坐标值,实现两坐标点的加、减运算

//你的代码将被嵌在这里

int main(){
    TwoCoor p1(1,2),p2(-1,1),p3,p4;
    p3=p1+p2;
    p4=p1-p2;
    p3.display();
    p4.display();
    return 0;
}

Sample Output

(0,3)
(2,1)

解题代码

#include <iostream>
using namespace std;
// TwoCoor类
class TwoCoor{
    // 成员 x值 y值
    int x ,y;
public:
    // 有参构造函数 初始化列表给x y赋值
    TwoCoor(int X,int Y){x = X;y = Y;}
    // 无参构造函数
    TwoCoor(){}
    // 运算符重载 +
    TwoCoor operator+(const TwoCoor & obj)
    {
        TwoCoor t;
        t.x = x + obj.x;
        t.y = y + obj.y;
        return t;
    }
    // 运算符重载 -
    TwoCoor operator-(const TwoCoor & obj)
    {
        TwoCoor t;
        t.x = x - obj.x;
        t.y = y - obj.y;
        return t;
    }
    // 打印点的坐标
    void display(){cout << "("<< x << "," << y << ")" << endl;}
};

习题练习(二十四)求两坐标点之间的距离

Problem Description

建立一个二维坐标系的类TwoCoor,用x、y表示坐标值,计算两坐标点间的距离

//你的代码将被嵌在这里
int main(){
    TwoCoor p1(3,0),p2(0,4);
    cout<<dist(p1,p2);
    return 0;
}

Sample Output

5

解题代码

// 导入相关头文件
#include <iostream>
// 用于计算的math库
#include <cmath>
using namespace std;
// TwoCoor类
class TwoCoor{
    // 成员 x y
    int x ,y;
public:
    // 构造函数 初始化列表初始化 x y的值
    TwoCoor(int X,int Y){x = X;y = Y;}
    // x y get函数
    int getX(){return x;}
    int getY(){return y;}
};
// 计算两点距离的函数
double dist(TwoCoor &o1,TwoCoor &o2)
{
    // 公式可以百度
    return sqrt((pow((o1.getX() - o2.getX()),2)+pow((o1.getY() - o2.getY()),2)));
}

习题练习(二十五)输入/输出坐标点的值

Problem Description

建立一个二维坐标系的类TwoCoor,用x、y表示坐标值,重载输入/输出运算符,使之能够直接输入/输出坐标点的坐标值。

//你的代码将被嵌在这里
int main(){
    TwoCoor p;
    cin>>p;    
    cout<<"点p是:"<<p;    
    return 0;
}

Sample Input

-3 6

Sample Output

点p是:(-3,6)

解题代码

#include <iostream>
using namespace std;
// TwoCoor类
class TwoCoor{
    // 成员 x y
    int x ,y;
public:
    // 使用友元的方式对输出符 >> 进行了重载
    friend istream & operator >> (istream &in,TwoCoor &obj)
    {
        // 从输入流接收两个int值并赋值给x y 
        in >> obj.x >> obj.y;
        // 返回输入流
        return in;
    }
    // 使用友元的方式对输出符 << 进行了重载
    friend ostream & operator << (ostream &out,TwoCoor &obj)
    {
        // 输出坐标点的信息到输出流
        out << "(" << obj.x << "," << obj.y << ")";
        // 返回输出流
        return out;
    }
};

习题练习(二十六)交换两个数

Problem Description

设计一个函数模板,实现两数的交换,并用int、float、char等类型的数据进行测试。

//你的代码将嵌在这里
int main()
{
         int i1=92,i2=-31;
         float f1=161.2f,f2=-3.6f;
         char c1='a',c2='M';
         cout<<"**********1**********\n";
         cout<<i1<<"\t"<<i2<<endl;
         change<int>(i1,i2);
         cout<<i1<<"\t"<<i2<<endl;
         cout<<"**********2**********\n";
         cout<<f1<<"\t"<<f2<<endl;
         change(f1,f2);
         cout<<f1<<"\t"<<f2<<endl;
         cout<<"**********3**********\n";
         cout<<c1<<"\t"<<c2<<endl;
         change(c1,c2);
         cout<<c1<<"\t"<<c2<<endl;
         return 0;
}

Sample Output

**********1**********
92	-31
-31	92
**********2**********
161.2	-3.6
-3.6	161.2
**********3**********
a	M
M	a

解题代码

#include <iostream>
using namespace std;
// 定义模板类型 这里也可以定义模板类
template <typename T>
// 函数模板 进行值的交换 一定要使用引用传递 使用值传递无法完成值的交换
void change(T & a,T & b)
{
    T temp = a;
    a = b;
    b = temp;
}

习题练习(二十七)建立两个int类型的向量

Problem Description

建立两个int类型的向量vector,利用merge算法将其合并,再用sort算法对合并后的向量排序。

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    int a[]={1,2,4,3,5,6};
    int b[]={2,3,1};
    vector<int> v1(a,a+6),v2(b,b+3),v3;
    vector<int>::iterator iter;
    //你的代码将嵌在这里

    for(iter=v3.begin();iter!=v3.end();iter++)
            cout<<*iter<<"\t";
    cout<<endl;    

    return 0;

}

Sample Output

1	1	2	2	3	3	4	5	6	

解题代码

// vector库的合并函数 
merge(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v3));
// vector库的排序函数
sort(v3.begin(),v3.end());
// 本题主要考察STL标准库vector的基本使用

习题练习(二十八) 定义点类Point

Problem Description

定义点类Point,其中有数据成员xy,表示点的横坐标与纵坐标。成员函数**double Distance(const Point &)*的功能是求两点之间的距离。请完善下面的程序。

//你的代码将被嵌在这里

int main()
{
    Point a,b;
    a.setPoint();
    b.setPoint();
    cout<<a.Distance(b);
    return 0;
}

Input Description

从键盘输入a点的横坐标、纵坐标;
从键盘输入b点的横坐标、纵坐标。

Output Description

在一行中输出点a和点b之间的距离。

Sample Input

0 0
3 4

Sample Output

5

解题代码

#include <iostream>
#include <cmath>
using namespace std;
// Point类
class Point{
    // 成员 x坐标 y坐标
    int x,y;
public:
    // 设置点的方法
    void setPoint()
    {
        // 从输入流接收两个int值 赋值给x y
        cin >> x >> y;
    }
    // 计算两点距离
    double Distance(const  Point & p)
    {
        // 这里隐藏了this-> 可以写成如下方式 点距离计算公式 百度一下 你就知道
        // return sqrt((pow((this->x - p.x),2) + pow((this->y - p.y),2)));
        return sqrt((pow((x - p.x),2) + pow((y - p.y),2)));
    }
};

习题练习(二十九)重载函数avg()

有int、double、long类型的数组,编写重载函数avg(),计算数组元素平均值。程序如下,请完善该程序。

//你的代码将被嵌在这里
int main(){
    int a[5]={2,39,-6,11,-100};
    int b[4]={5,6,1,28};
    double c[7]={72,-6.1,97,68.2,-51.3,-8,1234};
    long d[3]={658L,1489L,-256L};
    cout<<avg(a,5)<<endl;
    cout<<avg(b,4)<<endl;
    cout<<avg(c,7)<<endl;
    cout<<avg(d,3)<<endl;
    return 0;
}

Sample Output

-10
10
200.829
630

解题代码

#include <iostream>
using namespace std;
// 使用函数模板轻松解决 
// 不会真的有人写了三个函数吧!
template<typename T>
T avg(T *a,int n)
{
   // 将数组中的值累加
   T sum = 0;
   for(int i = 0;i < n;i++)
      sum += a[i];
    // 直接返回平均值
   return sum/n;
}
  • 26
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小宇0926

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值