首页 C++课程实习及答案全解

C++课程实习及答案全解

举报
开通vip

C++课程实习及答案全解C++课程实习及答案全解 1、字符串输入输出 描述:编写一个简单的控制台应用程序,先输入姓名,再输出问候语,如“Hello, John!”。 输入: John 输出: Hello, John! 输入样例: John 输出样例: Hello,John! 提示: 1、使用string类定义字符串对象,需包含头文件; 2、使用cin和提取符>>从键盘输入数据,使用cout和插入符; 3、注意使用名称空间std。 #include #include using namespace std; int ma...

C++课程实习及答案全解
C++课程实习及答案全解 1、字符串输入输出 描述:编写一个简单的控制台应用程序,先输入姓名,再输出问候语,如“Hello, John!”。 输入: John 输出: Hello, John! 输入样例: John 输出样例: Hello,John! 提示: 1、使用string类定义字符串对象,需包含头文件; 2、使用cin和提取符>>从键盘输入数据,使用cout和插入符<<输出结果到屏幕,需包含头文件; 3、注意使用名称空间std。 #include #include using namespace std; int main() { string szName; cin >> szName; cout << "Hello, " << szName << "!" << endl; return 0; } ----------------------------------------------------- 标题: 2、求3个数的平均值 描述:从键盘上输入3个浮点数,求这3个数的平均值。 输入:3个浮点数 输出: 3个数的平均值 输入样例: 1.5 1.6 1.3 输出样例: 1.46667 提示: 1、用using namespace std;明确名字空间 2、用cin对象,采用>>运算符输入数据 3、用cout对象,采用<<运算符输出数据 来源: 示例代码----------------------------------- #include using namespace std; int main() { float x1, x2, x3; cin>>x1>>x2>>x3; cout<<(x1+x2+x3)/3< using namespace std; int main() { int **mat; int *matRow, *matCol; int nMaxRow=0, nMaxCol=0; bool bFind=false; int nTargetRow=0, nTargetCol=0, nSaddlePoint=0; int i, j; //cout << "Please input the number of rows and the number of columns:" << endl; cin >> nMaxRow >> nMaxCol; //Allocate memories for the two dimensional matrices mat = new int *[nMaxRow]; for (i=0; i> mat[i][j]; //Find the minimum element in each row for (i=0; inMax) nMax = mat[i][j]; } matCol[j] = nMax; } //Find the saddle point for (i=0; i 记录 混凝土 养护记录下载土方回填监理旁站记录免费下载集备记录下载集备记录下载集备记录下载 ,则删除所有年龄等于此年龄的记录,否则在链表的最后增加一个新节点,学号为180姓名为"aaa",性别为"male"。。 输入:创建链表时输入5个职工的职工号和工资,学号为大于100且小于200的整数,姓名为长度小于20的字符串,性别为长度小于10的字符串,年龄为大于等于0且小于200的整数。 输出: 按顺序输出链表中的所有数据,每个数据占一行。 输入样例: 101 zhangsan male 30 103 lisi female 18 105 wangwu male 25 107 maliu male 28 109 niuqi female 22 28 输出样例: 101 zhangsan male 30 103 lisi female 18 105 wangwu male 25 109 niuqi female 22 提示: 要求用动态内存分配实现,注意new和delete的使用。 来源: 示例代码------------------------------------------------------------------------------------------------------- #include #include using namespace std; const int MAX_STR_LEN = 32; struct StuNode { 4 int ID; char name[MAX_STR_LEN]; char gender[MAX_STR_LEN]; int age; struct StuNode *next; }; typedef struct StuNode *StuLink; void CreateHeadNode(StuLink &pHead, StuLink &pTail) { pHead = new StuNode; if (pHead == NULL) return; pHead->next = NULL; pTail = pHead; } void AddStudent(StuLink &pTail, StuNode data) { StuLink p; p = new StuNode; if (p == NULL) return; p->ID = data.ID; strcpy(p->name, data.name); strcpy(p->gender, data.gender); p->age = data.age; p->next = NULL; //Make the current node pointer point to the last added data pTail->next = p; pTail = p; } bool RemoveStudent(StuLink &pHead, StuLink &pTail, int age) { bool bFind=false; StuLink pCurr, pPre; pPre = pHead; //Skip to the second node because the first node is the head node without data pCurr = pHead->next; 5 while (pCurr != NULL) { if (pCurr->age == age) { pPre->next = pCurr->next; delete pCurr; //Recover the current pointer to find the next node that has the same key pCurr = pPre->next; bFind=true; } else { //Move to the next node pPre = pCurr; pCurr = pCurr->next; } } //Recover the tail pointer in case the last node is deleted if(bFind && pPre->next==NULL) pTail = pPre; return bFind; } void OutputAllStudentsInfo(const StuLink pHead) { StuLink p; //Skip to the second node because the first node is the head node without data p = pHead->next; if (p == NULL) return; while (p != NULL) { cout << p->ID << endl; cout << p->name << endl; cout << p->gender << endl; cout << p->age << endl; p = p->next; } } void InputStudentInfo(StuNode &Emp) 6 { cin >> Emp.ID >> Emp.name >> Emp.gender >> Emp.age; while ( Emp.ID>=200 || Emp.ID<100 || strlen(Emp.name)>=20 || strlen(Emp.gender)>=10 || Emp.age<0 || Emp.age>=200) { cin >> Emp.ID >> Emp.name >> Emp.gender >> Emp.age; } } int main() { StuLink EmpInstHead, EmpInstTail; StuNode EmpTemp; int i, age; //Create a head node for the linked list CreateHeadNode(EmpInstHead, EmpInstTail); for (i=0; i<5; i++) { InputStudentInfo(EmpTemp); AddStudent(EmpInstTail, EmpTemp); } cin >> age; //Remove a head node from the linked list if(!RemoveStudent(EmpInstHead, EmpInstTail, age)) { EmpTemp.age = age; EmpTemp.ID=180; strcpy(EmpTemp.name, "aaa"); strcpy(EmpTemp.gender, "male"); EmpTemp.next=NULL; AddStudent(EmpInstTail, EmpTemp); } OutputAllStudentsInfo(EmpInstHead); return 0; } ---------------------------------------------------------------------------------------------------------------------- 1. 函数重载 描述: 设计一菜单程序,利用函数重载实现员工月工资的计算,计算方法如下: 7 (1)管理人员的月工资 , 月薪 , 缺勤天数 × 月薪 ? 22; (2)销售人员的月工资 , 底薪 + 销售金额 × 提成比例; (3)计件工人的月工资 , 产品件数 × 每件报酬; (4)计时工人的月工资 , 工作小时 × 小时报酬; 输入: 职工类别及相关信息。 职工类别:1表示管理人员;2表示销售人员;3表示计件工人;4表示计时工人;其余字符表示退出。 相关信息:若为管理人员,则输入月薪和缺勤天数;若为销售人员,则输入底薪、销售金额和提成比例;若为计件工人,则输入产品件数和每件报酬;若为计时工人,则输入工作小时和小时报酬。 输出: 员工月工资。 输入样例: 1 〈,,职工类别 5000.0 1〈,,月薪和缺勤天数 输出样例: 4772.73 提示: 1. 计算管理人员、销售人员、计件工人、计时工人的月工资的函数原型可以分别设计如下: double getEarning(double salary, int absenceDays); double getEarning(double baseSalary, double salesSum, double rate); double getEarning(int workPieces, double wagePerPiece); double getEarning(double hours, double wagePerHour); 2. 菜单程序设计如下: int main() { ... cout << "Please select..." << endl; cout << "1: Manager." << endl; cout << "2: Sales Man." << endl; cout << "3: Pieces Worker." << endl; cout << "4: Hour-Worker." << endl; cout << "Others: Quit" << endl; cin >> sel; switch(sel) { case 1: cin >> ...; cout << getEarning(...); break; case 2: cin >> ...; cout << getEarning(...); break; 8 case 3: cin >> ...; cout << getEarning(...); break; case 4: cin >> ...; cout << getEarning(...); break; default: break; } return 0; } #include using namespace std; double getEarning(double salary,int absenceDays) { return salary-absenceDays*salary/22; } double getEarning(double baseSlary,double salesSum,double rate) { return baseSlary+salesSum*rate; } double getEarning(int workPieces,double wagePerPiece) { return workPieces*wagePerPiece; } double getEarning(double hours,double wagePerHour) { return hours*wagePerHour; } int main() { double salary,baseSalary,salesSum,rate,hours,wagePerHour,wagePerPiece; int absenceDays,workPieces,sel; cout << "Please select..." << endl; cout << "1: Manager." << endl; cout << "2: Sales Man." << endl; 9 cout << "3: Pieces Worker." << endl; cout << "4: Hour-Worker." << endl; cout << "Others: Quit" << endl; cin >> sel; switch(sel) { case 1: cin >>salary>>absenceDays; cout << getEarning(salary,absenceDays); break; case 2: cin >> baseSalary>>salesSum>>rate; cout << getEarning(baseSalary,salesSum,rate); break; case 3: cin >> workPieces>>wagePerPiece; cout << getEarning(workPieces,wagePerPiece); break; case 4: cin >> hours>>wagePerHour; cout << getEarning(hours,wagePerHour); break; default: break; } return 0; } 示例代码-------------------------------------------------------------------------- #include using namespace std; double getEarning(double salary ,int absenceDays) { return (salary -salary*absenceDays/22); }// admin double getEarning(double baseSalary ,double salesSum,double rate) { return (baseSalary + salesSum*rate); } double getEarning(int workPieces,double wagePerPiece) { return (workPieces*wagePerPiece); } 10 double getEarning(double hours ,double wagePerHour) { return (hours*wagePerHour); } int main() { int kind = 0 ; cout << "Please select..." << endl; cout << "1: Manager." << endl; cout << "2: Sales Man." << endl; cout << "3: Pieces Worker." << endl; cout << "4: Hour-Worker." << endl; cout << "Others: Quit" << endl; cin >> kind ; switch(kind) { case 1: { double salary ; int abDays; cin>>salary>>abDays; cout<>base>>salesSum>>rate; cout<>workPieces>>wagePerPiece; cout<>hours>>wagePerHour; cout< using namespace std; void Math(float a , float b ,float& sum,float &sub,float&pro) { sum = a+ b ; sub = a-b ; pro = a*b ; } int main() { float sum = 0 ; float sub = 0 ; float pro = 0 ; float a = 0 ; float b = 0 ; cin>>a>>b; Math(a,b,sum,sub,pro); cout< using namespace std; template T cg(T &a ,T& b) { T c ; c = a ; a = b ; b = c ; } int main() { int a = 0 ; int b = 0 ; char c = 0 ; char d = 0 ; cin>>a>>b>>c>>d; cg(a,b); cg(c,d); cout< #include using namespace std; float distance(float x1,float y1,float z1,float x2=0,float y2=0,float z2=0) { return sqrt(pow(x1-x2,2)+pow(y1-y2,2)+pow(z1-z2,2)); } int main() { float x1 = 0 ; float x2 = 0 ; float y1 = 0 ; float y2 = 0 ; float z1 = 0 ; float z2 = 0 ; cin>>x1>>y1>>z1>>x2>>y2>>z2; cout< using namespace std; class Cylinder { private: double height,radius; 14 public: static const double Pi=3.1415926; Cylinder(double a=0,double b=0) { height=a; radius=b; } double GetPI() { return Pi; } void GetRadius() { cin >> radius; } void GetHeight() { cin >> height; } double SetRadius() { return radius; } double SetHeight() { return height; } double Volume() { return Pi*radius*radius*height; } double Area() { return 2*Pi*radius*height+2*Pi*radius*radius; } }; int main() { Cylinder y; y.GetHeight(); y.GetRadius(); cout << "pi=" << y.GetPI() << "," << " "; cout << "height=" << y.SetHeight() << "," << " "; 15 cout << "radius=" << y.SetRadius() << ":" ; cout << "volume=" << y.Volume() << "," <<" "; cout << "area=" << y.Area() < using namespace std; class Vect { public: Vect(int n=0); Vect(int arr[], int n); Vect(const Vect& v); ~Vect(); 16 int Size() { return arrSize; } int GetData(int i) { if(i<0 || i>=arrSize) { cout << "out of boundary" << endl; } else return arrData[i]; } void SetData(int i, int val) { if(i<0 || i>=arrSize) { cout << "out of boundary" << endl; } else arrData[i] = val; } void PrintData() { if(arrSize>0) cout << arrData[0]; for(int i=1; i> n; Vect v1(arr,5),v2(n); v1.PrintData(); v2.PrintData(); int i, data; cin >> i >> data; v1.SetData(i, data); Vect v3(v1); v1.PrintData(); 18 v3.PrintData(); return 0; } 标题: 虚基类 描述: (1)定义人员类Person: 公有成员:姓名(Name); 保护成员:性别(Gender),年龄(Age); 构造函数和析构函数 (2) 从人员类Person派生学生记录类StudentRecord: 添加公有成员:学号(Number),班级(ClassName), 添加静态公有成员:学生总人数(TotalCount); 添加保护成员:平均成绩(Score); 实现构造函数和析构函数。 (3) 从人员类Person派生教师记录类TeacherRecord: 添加公有成员:学院(CollegeName),系(DepartmentName); 添加保护成员:教龄(Year); 实现构造函数和析构函数。 (4)从学生记录类StudentRecord和教师记录类TeacherRecord派生学生助教类TeachingAssistant: 添加公有成员:辅导课程(LectureName); 实现公有函数:显示人员信息(Show),屏幕打印 姓名,性别,年龄,学号,班级,学生 总人数,平均成绩,学院,系,教龄,辅导课程。 实现构造函数和析构函数。为检验类间结构设计是否正确,设计函数void SetName(String name)实现更改一名助教的姓名的功能。 创建一个助教类的对象 助教 姓名 性别 年龄 学号 班级 平均成绩 学院 系 教龄 辅导课程 郑七 男 22 2010123 软20101 89 信息 软件 1 数据结构 显示其信息。 调用更改姓名的函数,更改其姓名为“郑八”,并再次显示其信息。 输入: 无 输出: 显示构造的信息和更改前和更改后的助教信息 输入样例: 无 输出样例: Person郑七constructed Student郑七constructed teacher郑七constructed teachingassistant郑七constructed Name:郑七 Gender:男 Age:22 Number:2010123 ClassName:软20101 TotalCount:1 Score:8 9 CollegeName:信息 DepartmentName:软件 Year:1 LectureName:数据结构 Name:郑八 Gender:男 Age:22 Number:2010123 ClassName:软20101 TotalCount:1 Score:8 9 CollegeName:信息 DepartmentName:软件 Year:1 LectureName:数据结构 19 teachingassistant郑八destructed teacher郑八destructed Student郑八destructed Person郑八destructed 提示: 各类的构造函数和析构函数都有输出。 调用公有函数Show,以分别显示各个记录的人员信息。 在派生助教类时,使用虚基类。 来源: #include #include using namespace std; class Person { protected: string Gender; int Age; public: string Name; Person(string gender, int age, string name) { Gender = gender; Age = age; //Name = new char[strlen(name)+1]; //strcpy(Name,name); Name = name; cout<<"Person"< #include using namespace std; class Point { public: 23 Point(double _x=0, double _y=0):x(_x),y(_y) { } public: double x; double y; }; class Line { public: Line(const Point &start, const Point &end):ptStart(start),ptEnd(end) { } double Length() { double len; len = sqrt((ptEnd.x-ptStart.x)*(ptEnd.x-ptStart.x) + (ptEnd.y-ptStart.y)*(ptEnd.y-ptStart.y)); return len; } private: Point ptStart; Point ptEnd; }; class Triangle { public: Triangle(const Point &p1, const Point &p2, const Point &p3):ptA(p1),ptB(p2),ptC(p3) { } double Perimeter(); double Area(); private: Point ptA; Point ptB; Point ptC; }; double Triangle::Perimeter() { Line lab(ptA,ptB), lbc(ptB,ptC), lca(ptC,ptA); 24 return lab.Length()+lbc.Length()+lca.Length(); } double Triangle::Area() { // 根据海伦公式计算三角形的面积 Line lab(ptA,ptB), lbc(ptB,ptC), lca(ptC,ptA); double a = lab.Length(); double b = lbc.Length(); double c = lca.Length(); double p = 0.5*(a+b+c); return sqrt(p*(p-a)*(p-b)*(p-c)); } int main() { // 依次输入三个点的坐标 double x1, y1, x2, y2, x3, y3; cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; // 输出三点所构成的三角形的周长和面积 Triangle t(Point(x1,y1),Point(x2,y2),Point(x3,y3)); cout << t.Perimeter() << " " << t.Area() << endl; return 0; } 标题: 继承和派生_链表 描述: 设计单链表类,并基于单链表类实现栈类和队列类: (1)设计学生信息类StudentRecord,要求包含公有数据成员:string stuName和int stuNo,设计用于输出学生信息的公有成员函数:void print,输出格式为:Name: stuName, Number: stuNo。 (2)设计学生链表的结点类StudentNode,要求包含公有数据成员:StudentRecord data和StudentNode *next。 (3)设计学生链表类LinkedList,要求定义头插入、头删除、尾插入、遍历等公有成员函数 (4)由LinkedList派生LinkedStack类,基于单链表类的功能实现压栈和出栈的成员函数:void Push(StudentRecord record)和bool Pop(StudentRecord &record)。 (5)由LinkedList派生LinkedQueue类,基于单链表类的功能实现入队和出队的成员函数:void EnQueue(StudentRecord record)和bool DeQueue(StudentRecord &record)。 在main函数中: 定义一个LinkedQueue类的对象queue和一个LinkedStack类的对象stack,并根据用户的输入分别对queue和stack作出相应的操作。若为"Push",则压栈;若为"EnQueue",则入队;若为"Pop",则出栈;若为"DeQueue",则出队;若为"Exit",则退出;若为其它,则给出提示信息"Input error!"。入栈和入队时,输入学生姓名和学号。出栈和出队时,若非空,则输出被删除的学生信息;若栈空,则输出Stack is empty!";若队空,则输出"Queue is empty!"。 25 输入: 操作名; 学生姓名,学号。 输出: 删除的信息;提示信息。 输入样例: Push ZhangSan 200905 Push LiSi 200906 EnQueue WangWu 200907 Pop exit Exit 输出样例: Name: LiSi, Number: 200906 Input error! 来源: #include #include using namespace std; // 学生信息类 class StudentRecord { public: StudentRecord(const string &name="", int number=0):stuName(name),stuNo(number) { } ~StudentRecord() { } void Print(); public: string stuName; int stuNo; }; void StudentRecord::Print() { cout << "Name: " << stuName << ", Number: " << stuNo << endl; } // 学生结点类 class StudentNode { public: 26 StudentNode(const StudentRecord &stu, StudentNode *pNext=NULL): data(stu), next(pNext) { } ~StudentNode() { } public: StudentRecord data; // 数据域 StudentNode *next; // 指针域 }; // 学生链表类 class LinkedList { public: LinkedList():head(0),tail(0) { } ~LinkedList() { while(head != 0) { FrontRemove(); } } StudentNode* HeadNode() { return head; } StudentNode* TailNode() { return tail; } void FrontInsert(const StudentRecord& stu) { StudentNode *t = new StudentNode(stu); t->next = head; head = t; } void FrontRemove() { if(head != 0) { StudentNode *t = head; 27 head = head->next; delete t; } } void BackInsert(const StudentRecord& stu) { StudentNode *t = new StudentNode(stu); if(tail != 0) { tail->next = t; } else { head = t; } tail = t; } void Print() { StudentNode *t = head; while(t != 0) { t->data.Print(); } } public: StudentNode *head; StudentNode *tail; }; class LinkedStack:public LinkedList { public: void Push(StudentRecord record) { FrontInsert(record); } bool Pop(StudentRecord &record) { if(head != 0) { record = HeadNode()->data; FrontRemove(); return true; 28 } else { return false; } } }; class LinkedQueue:public LinkedList { public: void EnQueue(StudentRecord record) { BackInsert(record); } bool DeQueue(StudentRecord &record) { if(head != 0) { record = HeadNode()->data; FrontRemove(); return true; } else { return false; } } }; int main() { LinkedQueue queue; LinkedStack stack; string szOp; while(szOp!="Exit") { cin >> szOp; if(szOp == "Push") { // 用入学生姓名、学号 string name; int num; 29 cin >> name >> num; stack.Push(StudentRecord(name, num)); } else if(szOp == "EnQueue") { // 用入学生姓名、学号 string name; int num; cin >> name >> num; queue.EnQueue(StudentRecord(name, num)); } else if(szOp == "Pop") { StudentRecord stu; if(stack.Pop(stu)) { stu.Print(); } else { cout << "Stack is empty!" << endl; } } else if(szOp == "DeQueue") { StudentRecord stu; if(queue.DeQueue(stu)) { stu.Print(); } else { cout << "Queue is empty!" << endl; } } else if(szOp == "Exit") { break; } else { cout << "Input error!" << endl; } } 30 return 0; } 标题: 抽象类与操作符重载 描述: 定义表示形状的抽象类及相应的派生类,并实现相关操作符重载。 (1)定义表示形状的抽象类Shape: 添加公有成员函数double Area(),用于计算形状面积;定义为纯虚函数; 添加公有成员函数void Show(),用于显示形状信息,定义为纯虚函数; 定义虚的析构函数; 重载比较操作符:==、>和<,用于比较两个形状面积的大小关系,返回值类型为bool,可以定义为成员函数或友元函数。 (2)从形状类Shape派生矩形类Rectangle: 添加double型的保护数据成员:rectWidth和rectHeight,分别表示矩形的宽度和高度; 定义带参构造函数; 重定义公有成员函数Show,打印矩形的宽度和高度,输出格式为“W: 宽度; H: 高度; Area: 面积”; 重定义公有成员函数Area,计算矩形面积。 (3)从形状类Shape派生椭圆类Ellipse: 添加double型的保护数据成员:rectWidth和rectHeight,分别表示椭圆外接矩形的宽度和高度; 定义带参构造函数; 重定义公有成员函数Show,打印椭圆外接矩形的宽度和高度,输出格式为“W: 宽度; H: 高度; Area: 面积”; 重定义公有成员函数Area,计算椭圆面积。 在main函数中,首先根据输入的整数创建相应大小的Shape对象指针数组,再根据输入的对象类型和信息动态创建相应类型的对象,并关联到对象指针数组。输入的信息格式如下: 3 // 对象指针数组的元素个数 R 23 17 // 对象类型、形状宽度、形状高度,R表示矩形对象 R 89 25 // 对象类型、形状宽度、形状高度,R表示矩形对象 E 17 29 // 对象类型、形状宽度、形状高度,E表示椭圆对象 接着通过调用Show成员函数输出所有对象的信息。 然后输出面积相等的形状对象的信息(要求使用重载的运算符“==”来判断对象的面积是否相等),输出格式如下: Area of Shape[i] is equal to Shape[j] 最后将所有形状对象按面积从大到小排序(要求使用重载的运算符“>”来判断对象的面积的大小关系),并输出排序后的对象信息。 输入: 对象数目 对象类型 对象的外接矩形宽度 对象的外接矩形高度 输出: 排序前的对象信息 面积相等的对象信息 排序后的对象信息 输入样例: 6 R 23 17 R 89 25 31 R 17 23 E 29 17 E 89 75 E 17 29 输出样例: W: 23; H:17; Area: 391 W: 89; H:25; Area: 2225 W: 17; H:23; Area: 391 W: 29; H:17; Area: 387.201 W: 89; H:75; Area: 5242.53 W: 17; H:29; Area: 387.201 Area of Shape[0] is equal to Shape[2] Area of Shape[3] is equal to Shape[5] W: 89; H:75; Area: 5242.53 W: 89; H:25; Area: 2225 W: 17; H:23; Area: 391 W: 23; H:17; Area: 391 W: 29; H:17; Area: 387.201 W: 17; H:29; Area: 387.201 来源: #include #include #include using namespace std; const double PI = 3.1415926; // 定义表示形状的抽象类 class Shape { public: Shape() {} virtual ~Shape() {} virtual double Area()=0; virtual void Show()=0; friend bool operator==(Shape &shLeft, Shape &shRight); friend bool operator<(Shape &shLeft, Shape &shRight); friend bool operator>(Shape &shLeft, Shape &shRight); }; bool operator==(Shape &shLeft, Shape &shRight) { return abs(shLeft.Area() - shRight.Area()) <= 1.0e-8; } bool operator<(Shape &shLeft, Shape &shRight) { 32 return shLeft.Area() < shRight.Area(); } bool operator>(Shape &shLeft, Shape &shRight) { return shLeft.Area() > shRight.Area(); } // 由Shape类派生得到矩形类 class Rectangle : public Shape { public: Rectangle(double w, double h); double Area(); void Show(); private: double rectWidth; double rectHeight; }; Rectangle::Rectangle(double w, double h): rectWidth(w), rectHeight(h) { } double Rectangle::Area() { return rectWidth * rectHeight; } void Rectangle::Show() { cout << "W: " << rectWidth << "; H:" << rectHeight << "; Area: " << Area() << endl; } // 由Shape类派生得到矩形类 class Eclipse : public Shape { public: Eclipse(double w, double h); double Area(); void Show(); private: double rectWidth; double rectHeight; }; Eclipse::Eclipse(double w, double h): 33 rectWidth(w), rectHeight(h) { } double Eclipse::Area() { return rectWidth * rectHeight * PI / 4; } void Eclipse::Show() { cout << "W: " << rectWidth << "; H:" << rectHeight << "; Area: " << Area() << endl; } int main() { // 创建具有指定元素个数的抽象指针数组 int shNum; cin >> shNum; Shape** shArr = new Shape*[shNum]; // 根据输入的信息依次创建对应的形状对象 char shType; // 形状类别:R-矩形;E-椭圆 double w, h; // 外接矩形的宽度和高度 for(int i=0; i> shType >> w >> h; switch(shType) { case 'R': { shArr[i] = new Rectangle(w,h); break; } case 'E': { shArr[i] = new Eclipse(w,h); break; } } } // 输出对象信息 for(int i=0; iShow(); 34 } // 比较所有形状对象,输出面积相等的两个形状对象对应的数组下标 for(int i=0; i *shArr[k]) { k =j; } } shTemp = shArr[i]; shArr[i] = shArr[k]; shArr[k] = shTemp; } // 输出排序后的对象信息 for(int i=0; iShow(); } // 销毁对象 for(int i=0; i #include #include 36 using namespace std; class Person { public: Person(const string& name); virtual void Print() const; protected: string szName; }; Person::Person(const string& name):szName(name) { } void Person::Print() const { cout << "Person " << szName << endl; } class Student : public Person { public: Student(const string& name, int number); void Print() const; protected: int iNumber; }; Student::Student(const string& name, int number):Person(name),iNumber(number) { } void Student::Print() const { cout << "Student " << szName << " " << iNumber << endl; } class Teacher : public Person { public: 37 Teacher(const string& name, int year); void Print() const; protected: int iYear; }; Teacher::Teacher(const string& name, int year):Person(name),iYear(year) { } void Teacher::Print() const { cout << "Teacher " << szName << " " << iYear << endl; } class Graduate : public Student { public: Graduate(const string& name, int number, string major); void Print() const; protected: string szResearch; }; Graduate::Graduate(const string& name, int number, string major): Student(name, number), szResearch(major) { } void Graduate::Print() const { cout << "Graduate " << szName << " " << iNumber << " " << szResearch << endl; } int main() { // 对象指针数组长度 int psNum; cin >> psNum; // 对象指针数组 Person* *psArr = new Person*[psNum]; 38 // 对象类型、姓名、学号、教龄、研究方向 string szType, szName, szMajor; int iNumber, iYear; // 根据输入的对象信息创建不同类型的对象 for(int i=0; i> szType; if(szType == "Person") { cin >> szName; psArr[i] = new Person(szName) ; } else if(szType == "Student") { cin >> szName >> iNumber; psArr[i] = new Student(szName, iNumber); } else if(szType == "Teacher") { cin >> szName >> iYear; psArr[i] = new Teacher(szName, iYear); } else if(szType == "Graduate") { cin >> szName >> iNumber >> szMajor; psArr[i] = new Graduate(szName, iNumber, szMajor); } else { } } // 需要打印信息的对象下标 string szIdx; int objIdx; cin >> szIdx; while(szIdx != "exit") { // 对象下标 objIdx = atoi(szIdx.c_str()); objIdx = max(0, min(objIdx, psNum)); 39 // 输出对象信息 psArr[objIdx]->Print(); cin >> szIdx; } // 释放对象内存 for(int i=0; i、>=重载为友员函数,实现有理数的大小关系比较。 (8)重载流插入符<<和流提取符>>,分别用于有理数的输出和输入。其中,输出格式为“分子/分母”,若为整数,则直接输出整数。 在main函数中,根据输入的分子和分母定义两个有理数对象a和b。再定义几个有理数对象分别用于表示a和b的加、减、乘、除、前置自增a、前置自减a、后置自增a、后置自减a,并依次各个对象的结果。最后依次用<、<=、>、>=比较a和b的大小关系,并依次输出比较结果(true或false)。 输入: 两个有理数a和b的的分子和分母 输出: 有理数a和b的加、减、乘、除以及前置自增a、前置自减a、后置自增a、后置自减a 有理数a和b的<、<=、>、>=的结果 输入样例: 4 3 3 2 40 输出样例: a+b: 17/6 a-b: -1/6 a*b: 2 a/b: 8/9 -a: 1/3 ++a: 4/3 --a: 1/3 a++: 1/3 a--: 4/3 ab: false a>=b: false 来源: #include #include #include #include using namespace std; // 定义有理数类:分子分母均为整数,分母不为0 class Rational { public: // 构造函数 Rational(int up = 0, int down = 1); // 有理数的倒数 Rational Invert() const; // 有理数的负数 Rational operator-() const; // 赋值运算符重载 Rational& operator=(const Rational& r); // 前置++ Rational& operator++(); // 后置++ Rational operator++(int); // 前置-- Rational& operator--(); // 后置-- Rational operator--(int); // 有理数相加 friend Rational operator+(const Rational &l, const Rational &r); // 有理数相减 friend Rational operator-(const Rational &l, const Rational &r); // 有理数相乘 friend Rational operator*(const Rational &l, const Rational &r); // 有理数相除 friend Rational operator/(const Rational &l, const Rational &r); // 两个有理数是否相等 friend bool operator==(const Rational &l, const Rational &r); // 两个有理数的大小关系 41 friend bool operator<(const Rational &l, const Rational &r); // 两个有理数的大小关系 friend bool operator>(const Rational &l, const Rational &r); // 两个有理数的大小关系 friend bool operator<=(const Rational &l, const Rational &r); // 两个有理数的大小关系 friend bool operator>=(const Rational &l, const Rational &r); // 流插入符重载 friend ostream& operator<<(ostream& os, const Rational& rat); // 流提取符重载 friend istream& operator>>(istream& is, Rational& rat); private: // 分数约简 void Simplify(); private: int iUp; // 分子 int iDown; // 分母 };// 构造函数 Rational::Rational(int up, int down):iUp(up),iDown(down) { // 分数约简 Simplify(); } // 分数约简 void Rational::Simplify() { int m, n, r, s = 1; if(iUp != 0 && iDown != 0) { // 保证分母为正数,s表示分数的符号,计在分子上 if(iDown < 0) { s = -s; iDown = -iDown; } if(iUp < 0) { s = -s; iUp = -iUp; } // 利用辗转相除法求最大公约数 42 m = iUp; n = iDown; while(n != 0) { r = m % n; m = n; n = r; } // 利用最大公约数约简分数 if(m != 0) { iUp = s * iUp / m; iDown = iDown / m; } } else { iUp = 0; iDown = 1; } } // 创建有理数的倒数副本 Rational Rational::Invert() const { return Rational(iDown, iUp); } // 创建有理数的负数副本 Rational Rational::operator-() const { return Rational(-iUp, iDown); } // 赋值运算符的重载 Rational& Rational::operator=(const Rational& r) { if(this != &r) { iUp = r.iUp; iDown = r.iDown; } 43 return *this; } // 前置++,实现有理数自增1 Rational& Rational::operator++() { iUp += iDown; // 分数约简 Simplify(); return *this; } // 后置++,实现有理数自增1 Rational Rational::operator++(int) { Rational t = *this; iUp += iDown; // 分数约简 Simplify(); return t; } // 前置--,实现有理数自减1 Rational& Rational::operator--() { iUp -= iDown; // 分数约简 Simplify(); return *this; } // 后置--,实现有理数自减1 Rational Rational::operator--(int) { Rational t = *this; iUp -= iDown; // 分数约简 Simplify(); 44 return t; } Rational operator+(const Rational &l, const Rational &r) { int m = l.iUp * r.iDown + l.iDown * r.iUp; int n = l.iDown * r.iDown; // 分数约简 Rational t(m, n); return t; } Rational operator-(const Rational &l, const Rational &r) { int m = l.iUp * r.iDown - l.iDown * r.iUp; int n = l.iDown * r.iDown; // 分数约简 Rational t(m, n); return t; } Rational operator*(const Rational &l, const Rational &r) { int m = l.iUp * r.iUp; int n = l.iDown * r.iDown; Rational t(m, n); return t; } Rational operator/(const Rational &l, const Rational &r) { int m = l.iUp * r.iDown; int n = l.iDown * r.iUp; Rational t(m, n); return t; } bool operator==(const Rational& l, const Rational& r) 45 { return (l.iUp * r.iDown) == (l.iDown * r.iUp); } bool operator<(const Rational& l, const Rational& r) { return (l.iUp * r.iDown) < (l.iDown * r.iUp); } bool operator>(const Rational& l, const Rational& r) { return (l.iUp * r.iDown) > (l.iDown * r.iUp); } bool operator<=(const Rational& l, const Rational& r) { return (l.iUp * r.iDown) <= (l.iDown * r.iUp); } bool operator>=(const Rational& l, const Rational& r) { return (l.iUp * r.iDown) >= (l.iDown * r.iUp); } ostream& operator<<(ostream& os, const Rational& rat) { if(rat.iDown == 1) os << rat.iUp; else os << rat.iUp << "/" << rat.iDown; return os; } istream& operator>>(istream& is, Rational& rat) { is >> rat.iUp >> rat.iDown; return is; } int main() { Rational a, b; 46 // 输入有理数a的分子和分母 //cout << "Enter the numerator and denominator for Rational a: "; cin >> a; // 输入有理数b的分子和分母 //cout << "\nEnter the numerator and denominator for Rational b: "; cin >> b; Rational s = a + b; Rational d = a - b; Rational p = a * b; Rational q = a / b; cout << "a+b: " << s << endl; cout << "a-b: " << d << endl; cout << "a*b: " << p << endl; cout << "a/b: " << q << endl; Rational nga = --a; // 负a Rational ppa = ++a; // 前置自增a Rational rra = --a; // 前置自减a Rational app = a++; // 后置自增a Rational arr = a--; // 后置自减a cout << "-a: " << nga << endl; cout << "++a: " << ppa << endl; cout << "--a: " << rra << endl; cout << "a++: " << app << endl; cout << "a--: " << arr << endl; cout << "ab: " << boolalpha << (a>b) << endl; cout << "a>=b: " << boolalpha << (a>=b) << endl; return 0; } 标题: 利用STL中的multimap查找共同好友 描述: 利用multimap查找共同好友并输出 输入: 所有好友记录的个数 所有好友记录的信息 要查找多少人的共同好友 47 要查找哪些人(姓名)的共同好友 输出: 共同好友的全部信息(包括;)按照num排序输出,如果没有,输出NO 输入样例: 6 张潮 刘磊 902419 22 王磊 赵磊 902429 22 张潮 张平一 902436 21 李平一 白上由 902422 22 王浩 王洗星 902420 20 王浩 张平一 902436 21 2 张潮 王浩 输出样例: 张平一 902436 21 提示: 相同好友是指 姓名 学号 年龄 全部相同 来源: #include #include #include using namespace std; typedef pair PairNumAge ; typedef pair Friends ; typedef pair Psf ; class MyFriend { public : Friends Information ; MyFriend(Friends _info):Information(_info) { ; } MyFriend() { ; } int operator == (MyFriend &temp) { if(Information.first == temp.Information.first &&Information.second.first ==temp.Information.second.first &&Information.second.second ==temp.Information.second.second) return 1; return 0 ; 48 } void operator = (MyFriend &temp) { Information.first = temp.Information.first ; Information.second.first =temp.Information.second.first; Information.second.second =temp.Information.second.second; } } ; istream& operator >>(istream& in ,Psf* &PairTemp) { in >>PairTemp->first >>PairTemp->second.first >>PairTemp->second.second.first >>PairTemp->second.second.second; return in ; } ostream& operator <<(ostream& out ,MyFriend& temp) { out < &friendMap) { multimap::iterator PairFind ; PairFind = friendMap.begin(); } void FindTheFriendAndPrint(string *_Tname,multimap& friendMap,int n) { multimap::iterator PairPerson[n] ; MyFriend temp ; int flag = 0 ; for(int i = 1 ; i < n ; i ++) { for(PairPerson[i-1] = friendMap.lower_bound(_Tname[i-1]); PairPerson[i-1]!= friendMap.upper_bound(_Tname[i-1]); PairPerson[i-1]++) { for(PairPerson[i] = friendMap.lower_bound(_Tname[i]); 49 PairPerson[i]!= friendMap.upper_bound(_Tname[i]); PairPerson[i]++ ) { if(PairPerson[i-1]->second ==PairPerson[i]->second) { flag ++ ; temp = PairPerson[i-1]->second ; } } } if(flag < i) break ; } if(flag == n-1) { cout <friendMap ; Psf *PairTemp ; int n ; cin >> n ; for(int i = 0 ; i < n ; i ++ ) { PairTemp = new Psf ; cin >>PairTemp ; friendMap.insert(*PairTemp) ; } PrintfFriendMap(friendMap) ; cin >> n ; string *_Tname ; _Tname = new string[n] ; for(int i = 0 ; i < n ; i ++ ) { cin >>_Tname[i] ; } FindTheFriendAndPrint(_Tname,friendMap,n); 50 return 0 ; } 标题: 利用STL中的map统计单词出现频次 描述: 使用string类和STL相关容器统计输入文本中所有单词出现的次数。要求:(1)单词统计不分大小写,如Cambridge和CAMBRIDGE是同一单词;(2)标点符号“,.;!?”需要过滤;(3)输出结果按照字母大小从小到大排列且输出单词必须是小写,如Cambridge应转化为cambridge后输出。 输入: 键盘输入文本信息,“exit”为文本结束标志。 输出: 文本中出现的所有单词和频率(次数)。注意单词和频率之间用空格隔开,最后一个输出字符串后面还有一个空格。 输入样例: SAYING GOODBYE TO CAMBRIDGE AGAIN Very quietly I left As quietly as I came here; Quietly I wave goodbye To the rosy clouds in the western sky. The golden willows by the riverside Are young brides in the setting sun; Their reflections on the shimmering waves Always linger in the depth of my heart. The floatingheart growing in the sludge Sways leisurely under the water; In the gentle waves of Cambridge I would be a water plant! exit 输出样例: a 1 again 1 always 1 are 1 as 2 be 1 brides 1 by 1 cambridge 2 came 1 clouds 1 depth 1 floatingheart 1 gentle 1 golden 1 goodbye 2 growing 1 heart 1 here 1 i 4 in 5 left 1 leisurely 1 linger 1 my 1 of 2 on 1 plant 1 quietly 3 reflections 1 riverside 1 rosy 1 saying 1 setting 1 shimmering 1 sky 1 sludge 1 sun 1 sways 1 the 11 their 1 to 2 under 1 very 1 water 2 wave 1 waves 2 western 1 willows 1 would 1 young 1 提示: 使用STL中的map,字符查找函数find和字符小写转换函数tolower。 来源: #include #include #include #include #include using namespace std ; ostream& operator << (ostream & out ,pair temp ) { cout < Data ; string temp ; cin >>temp ; while(temp!= "exit") { transform(temp.begin(),temp.end(),temp.begin(),::tolower) ; DealWithString(temp) ; if(Data.find(temp) != Data.end()) { Data[temp] ++ ; } else { Data.insert(make_pair(temp,1)) ; } cin >>temp ; } map::iterator MapIte ; int i = 0 ; for(MapIte = Data.begin() ; MapIte != Data.end() ; MapIte ++) 52 { i++ ; cout << *MapIte; } return 0 ; } 标题: 记录文件的读写操作 描述: 源数据文件(文本格式)中包含有每个学生的记录:ID(身份识别号)、 Gender(性别)、 Birthday(生日)和EnrollmentDate(入学时间),字段之间以半角逗号分隔,记录之间以换行符 分隔。要求从源数据文件中读取学生记录并删除重复记录,然后根据ID大小对所有记录按 从小到大排序,将排序后的记录保存到目标文件中并同时输出到屏幕上。 输入: 键盘输入源文件和目标文件的文件名 输出: 将处理后的学生记录输出到目标文件和屏幕 输入样例: 源数据文件和目标数据文件名: SrcData.txt DstData.txt 源数据文件内容: 10001,F,1987/4/1,2006/9/1 10005,F,1989/11/30,2008/9/1 10005,F,1989/11/30,2008/9/1 10006,M,1986/3/14,2005/9/1 10002,M,1988/5/5,2006/9/1 10003,M,1985/8/13,2005/4/1 10004,M,1985/12/15,2006/4/1 10003,M,1985/8/13,2005/4/1 输出样例: 目标文件和屏幕打印的内容: 10001,F,1987/4/1,2006/9/1 10002,M,1988/5/5,2006/9/1 10003,M,1985/8/13,2005/4/1 10004,M,1985/12/15,2006/4/1 10005,F,1989/11/30,2008/9/1 10006,M,1986/3/14,2005/9/1 来源: #include #include #include #include #include #include using namespace std ; int main() 53 { vector DocuData ; char InputDocName[50]; char OutputDocName[50] ; cin >>InputDocName >> OutputDocName ; ifstream from(InputDocName) ; if(!from) { cout <<"ERROR\n" ; return -1 ; } string line ; while(getline(from,line)) { DocuData.push_back(line) ; } sort(DocuData.begin(),DocuData.end()) ; unique_copy(DocuData.begin(),DocuData.end(), ostream_iterator(cout,"\n")) ; ofstream out(OutputDocName) ; if(!out) { cout <<"ERROR\n" ; return -1 ; } unique_copy(DocuData.begin(),DocuData.end(), ostream_iterator(out,"\n")) ; from.close() ; out.close() ; return 0 ; } 标题:简单文本文件的读写 描述:逐行读取源文件的文本,在每行文本前加上行号,保存到目标文件并同时输出到屏幕。 输入:键盘输入源文件和目标文件的文件名 输出:将添加行号后的文本输出到目标文件和屏幕 输入样例: 源文件和目标文件名: SrcData.txt DstData.txt 源文件内容: #include using namespace std; 54 int main() { cout << "Hello world!" << endl; return 0; } 输出样例: 目标文件及屏幕输出结果: 0001 #include 0002 0003 using namespace std; 0004 0005 int main() 0006 { 0007 cout << "Hello world!" << endl; 0008 return 0; 0009 } 提示: 本机测试时,可在项目的当前路径下建立一个名为SrcData.txt的源文本文件。 利用getline函数读取行数据;利用setfill和setw格式控制符设置输出格式。 #include #include #include #include #include using namespace std; int main() { unsigned int i; string filename; cin >> filename; ifstream in(filename.c_str()); string line; vector v; while(getline(in,line)) v.push_back(line); for(i=0;i
本文档为【C++课程实习及答案全解】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_751406
暂无简介~
格式:doc
大小:165KB
软件:Word
页数:94
分类:互联网
上传时间:2017-11-13
浏览量:173