计算与人工智能概论-问题求解、科学计算与AI应用方法 习题及答案 第8章参考答案_第1页
计算与人工智能概论-问题求解、科学计算与AI应用方法 习题及答案 第8章参考答案_第2页
计算与人工智能概论-问题求解、科学计算与AI应用方法 习题及答案 第8章参考答案_第3页
计算与人工智能概论-问题求解、科学计算与AI应用方法 习题及答案 第8章参考答案_第4页
计算与人工智能概论-问题求解、科学计算与AI应用方法 习题及答案 第8章参考答案_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

创建一个名为Person的结构体,包含姓名(字符串)和年龄(整数),然后创建两个Person结构体实例,并使用指针交换这两个实例的内容。#include<iostream>#include<cstring>usingnamespacestd;structPerson{charname[50];intage;};intmain(){Personp1={"Alice",25};Personp2={"Bob",30};Person*ptr1=&p1;Person*ptr2=&p2;cout<<"交换前:"<<endl;cout<<"p1:"<<ptr1->name<<","<<ptr1->age<<"岁"<<endl;cout<<"p2:"<<ptr2->name<<","<<ptr2->age<<"岁"<<endl;Persontemp=*ptr1;*ptr1=*ptr2;*ptr2=temp;cout<<"交换后:"<<endl;cout<<"p1:"<<ptr1->name<<","<<ptr1->age<<"岁"<<endl;cout<<"p2:"<<ptr2->name<<","<<ptr2->age<<"岁"<<endl;return0;}定义一个名为Rectangle的结构体,包含长度和宽度(浮点数)。编写一个函数,接收一个Rectangle类型的参数,并返回该矩形的面积和周长。#include<iostream>usingnamespacestd;//定义矩形结构体structRectangle{doublelength;doublewidth;};//定义用于返回面积和周长的结果结构体structRectResult{doublearea;doubleperimeter;};//函数:接收Rectangle,返回面积和周长RectResultgetAreaAndPerimeter(Rectanglerect){RectResultresult;result.area=rect.length*rect.width;result.perimeter=2.0*(rect.length+rect.width);returnresult;}intmain(){Rectangler={5.0,3.0};RectResultres=getAreaAndPerimeter(r);cout<<"矩形长="<<r.length<<",宽="<<r.width<<endl;cout<<"面积:"<<res.area<<endl;cout<<"周长:"<<res.perimeter<<endl;return0;}定义一个枚举类型Color,包含红色、绿色和蓝色三种颜色。编写一个程序,创建一个枚举变量,并根据用户输入的颜色名称设置其值,最后输出当前的颜色。#include<iostream>#include<string>usingnamespacestd;enumColor{RED,GREEN,BLUE};intmain(){ColorcurrentColor;stringinput;cout<<"请输入颜色(red/green/blue):";cin>>input;//将输入转换为小写以便比较for(char&c:input){c=tolower(c);}if(input=="red"){currentColor=RED;}elseif(input=="green"){currentColor=GREEN;}elseif(input=="blue"){currentColor=BLUE;}else{cout<<"无效的颜色输入!默认设置为红色。"<<endl;currentColor=RED;}//输出当前颜色switch(currentColor){caseRED:cout<<"当前颜色是:红色"<<endl;break;caseGREEN:cout<<"当前颜色是:绿色"<<endl;break;caseBLUE:cout<<"当前颜色是:蓝色"<<endl;break;}return0;}定义一个联合Data,包含整数、浮点数和字符数组三个成员。编写一个程序,演示如何在这些成员之间切换存储数据,并输出当前存储的数据类型及值。#include<iostream>#include<cstring>usingnamespacestd;unionData{inti;floatf;charstr[20];};intmain(){Datadata;intchoice;cout<<"请选择要存储的数据类型:\n";cout<<"1.整数\n2.浮点数\n3.字符串\n";cout<<"请输入选项(1-3):";cin>>choice;//清空输入缓冲区cin.ignore();switch(choice){case1:{intvalue;cout<<"请输入一个整数:";cin>>value;data.i=value;cout<<"\n当前存储的是整数:"<<data.i<<endl;break;}case2:{floatvalue;cout<<"请输入一个浮点数:";cin>>value;data.f=value;cout<<"\n当前存储的是浮点数:"<<data.f<<endl;break;}case3:{charinput[20];cout<<"请输入一个字符串(不超过19个字符):";cin.getline(input,20);strcpy(data.str,input);cout<<"\n当前存储的是字符串:"<<data.str<<endl;break;}default:cout<<"无效选项!"<<endl;return1;}//演示联合的特性:访问其他成员会得到无意义的值cout<<"\n---联合内存共享演示---"<<endl;cout<<"联合当前各成员的值(仅最后赋值的成员有效):\n";cout<<"整数成员i="<<data.i<<endl;cout<<"浮点数成员f="<<data.f<<endl;cout<<"字符串成员str=\""<<data.str<<"\""<<endl;cout<<"\n注意:只有最后写入的成员包含有效数据,其他成员的值是未定义的!"<<endl;return0;}定义一个名为Date的结构体,包含年、月、日(均为整数)。编写一个函数,判断给定日期是否为闰年,并输出结果。#include<iostream>usingnamespacestd;structDate{intyear;intmonth;intday;};//判断是否为闰年的函数(仅需年份)boolisLeapYear(intyear){if((year%4==0&&year%100!=0)||(year%400==0)){returntrue;}returnfalse;}//接收Date类型参数,判断其年份是否为闰年voidcheckLeapYear(Dated){cout<<"日期:"<<d.year<<"-"<<d.month<<"-"<<d.day<<endl;if(isLeapYear(d.year)){cout<<d.year<<"年是闰年。"<<endl;}else{cout<<d.year<<"年不是闰年。"<<endl;}}intmain(){Dated1={2024,2,29};Dated2={2023,3,15};Dated3={1900,1,1};Dated4={2000,12,31};checkLeapYear(d1);checkLeapYear(d2);checkLeapYear(d3);checkLeapYear(d4);return0;}定义一个名为Student的结构体,包含学号、姓名和成绩(均为整数)。编写一个程序,使用结构数组存储多个学生的数据,并实现按成绩排序的功能。#include<iostream>#include<cstring>usingnamespacestd;structStudent{intid;//学号charname[50];//姓名intscore;//成绩};//使用冒泡排序按成绩升序排列(通过指针操作结构数组)voidsortStudentsByScore(Student*students,intn){for(inti=0;i<n-1;i++){for(intj=0;j<n-1-i;j++){if((students+j)->score>(students+j+1)->score){//交换两个结构体Studenttemp=*(students+j);*(students+j)=*(students+j+1);*(students+j+1)=temp;}}}}intmain(){constintN=5;Studentstudents[N]={{1001,"张三",85},{1002,"李四",92},{1003,"王五",78},{1004,"赵六",96},{1005,"钱七",88}};cout<<"排序前的学生信息:"<<endl;for(inti=0;i<N;i++){cout<<"学号:"<<students[i].id<<",姓名:"<<students[i].name<<",成绩:"<<students[i].score<<endl;}//调用排序函数(传递数组首地址)sortStudentsByScore(students,N);cout<<"\n按成绩升序排序后的学生信息:"<<endl;for(inti=0;i<N;i++){cout<<"学号:"<<students[i].id<<",姓名:"<<students[i].name<<",成绩:"<<students[i].score<<endl;}return0;}定义一个名为Point的结构体,包含坐标x和y(均为浮点数)。编写一个函数,接收两个Point类型的参数,并计算这两点之间的距离。#include<iostream>#include<cmath>//用于sqrt函数usingnamespacestd;//定义Point结构体structPoint{doublex;doubley;};//计算两点之间距离的函数doubledistance(Pointp1,Pointp2){doubledx=p2.x-p1.x;doubledy=p2.y-p1.y;returnsqrt(dx*dx+dy*dy);}intmain(){Pointa={0.0,0.0};Pointb={3.0,4.0};doubledist=distance(a,b);cout<<"点("<<a.x<<","<<a.y<<")与点("<<b.x<<","<<b.y<<")之间的距离为:"<<dist<<endl;//可选:交互式输入Pointp1,p2;cout<<"\n请输入第一个点的坐标(xy):";cin>>p1.x>>p1.y;cout<<"请输入第二个点的坐标(xy):";cin>>p2.x>>p2.y;doubleuserDist=distance(p1,p2);cout<<"两点之间的距离为:"<<userDist<<endl;return0;}定义一个类Circle,包含半径(浮点数)作为私有成员。提供公有成员函数来计算圆的面积和周长,并允许设置和获取半径的值。编写主函数测试这些功能。#include<cmath>usingnamespacestd;classCircle{private:doubleradius;//私有成员:半径public://构造函数(带默认参数)Circle(doubler=0.0){setRadius(r);}//设置半径(带有效性检查)voidsetRadius(doubler){if(r>=0){radius=r;}else{cout<<"警告:半径不能为负数,已设为0。"<<endl;radius=0.0;}}//获取半径doublegetRadius()const{returnradius;}//计算面积doublegetArea()const{returnM_PI*radius*radius;}//计算周长doublegetCircumference()const{return2*M_PI*radius;}};intmain(){//测试1:使用默认构造Circlec1;cout<<"圆1-半径:"<<c1.getRadius()<<",面积:"<<c1.getArea()<<",周长:"<<c1.getCircumference()<<endl;//测试2:设置有效半径Circlec2(5.0);cout<<"圆2-半径:"<<c2.getRadius()<<",面积:"<<c2.getArea()<<",周长:"<<c2.getCircumference()<<endl;//测试3:动态修改半径c2.setRadius(3.0);cout<<"修改后圆2-半径:"<<c2.getRadius()<<",面积:"<<c2.getArea()<<",周长:"<<c2.getCircumference()<<endl;//测试4:尝试设置负半径(验证错误处理)Circlec3;c3.setRadius(-2.5);//应触发警告并设为0cout<<"圆3-半径:"<<c3.getRadius()<<",面积:"<<c3.getArea()<<",周长:"<<c3.getCircumference()<<endl;return0;}定义一个模板类Pair,包含两个任意类型的成员。提供成员函数来交换这两个成员的值。编写主函数,测试不同类型的Pair实例。#include<iostream>#include<string>usingnamespacestd;//定义模板类Pairtemplate<typenameT1,typenameT2>classPair{private:T1first;T2second;public://构造函数Pair(constT1&f,constT2&s):first(f),second(s){}//获取成员T1getFirst()const{returnfirst;}T2getSecond()const{returnsecond;}//设置成员voidsetFirst(constT1&f){first=f;}voidsetSecond(constT2&s){second=s;}//交换两个成员的值(仅当类型相同时才有效)//注意:由于T1和T2可能不同,直接交换会导致类型不匹配//因此我们提供一个条件编译版本,或说明限制//实际上,只有当T1==T2时才能安全交换//但题目要求“交换这两个成员的值”,我们假设在类型相同时使用//或者更合理的方式是:仅在主函数中对同类型Pair调用swap//更通用的做法:不提供跨类型的swap,而是让用户自己处理//但为了满足题目,我们提供一个swap函数,并在主函数中只用于同类型PairvoidswapMembers(){//只有当T1和T2是相同类型时,以下代码才有意义//否则会编译错误或逻辑错误//在C++17中可用ifconstexpr判断,但为兼容性,我们依赖用户正确使用T1temp=first;first=static_cast<T1>(second);//可能需要转换second=static_cast<T2>(temp);//注意:这种强制转换可能不安全!//更好的设计是:只对同类型Pair提供swap//因此,我们在主函数中主要测试同类型的Pair}//打印函数(用于测试)voidprint()const{cout<<"Pair("<<first<<","<<second<<")"<<endl;}};//特化:为同类型提供安全的swap(可选增强)//但题目未要求,我们简化处理intmain(){//测试1:整数和浮点数(不同类型,swap可能不安全,故不调用swap)Pair<int,double>p1(10,3.14);cout<<"p1:";p1.print();//测试2:两个整数(同类型,可以安全交换)Pair<int,int>p2(5,8);cout<<"p2原始:";p2.print();p2.swapMembers();cout<<"p2交换后:";p2.print();//测试3:两个字符串Pair<string,string>p3("Hello","World");cout<<"p3原始:";p3.print();p3.swapMembers();cout<<"p3交换后:";p3.print();//测试4:字符和整数(不同类型,不建议swap)Pair<char,int>p4('A',65);cout<<"p4:";p4.print();//如果尝试对p4调用swapMembers(),可能会因类型转换产生意外结果//例如:first=(char)65->'A',second=(int)'A'->65,看起来没变//但在其他值下可能出错,因此swap应谨慎使用return0;}定义一个类Employee,包含员工的基本信息(如姓名、职位、工资等)。提供构造函数初始化对象,并提供成员函数显示员工的信息。#include<iostream>#include<string>usingnamespacestd;classEmployee{private:stringname;//姓名stringposition;//职位doublesalary;//工资public://构造函数:用于初始化员工对象Employee(conststring&n,conststring&pos,doubles):name(n),position(pos),salary(s){//可选:对工资做有效性检查if(salary<0){cout<<"警告:工资不能为负数,已设为0。"<<endl;salary=0.0;}}//默认构造函数(可选)Employee():name("未知"),position("无职位"),salary(0.0){}//显示员工信息的成员函数voiddisplayInfo()const{cout<<"姓名:"<<name<<"\n职位:"<<position<<"\n工资:$"<<salary<<endl;}//提供getter和setter(可选,增强实用性)stringgetName()const{returnname;}stringgetPosition()const{returnposition;}doublegetSalary()const{returnsalary;}voidsetPosition(conststring&pos){position=pos;}voidsetSalary(doubles){if(s>=0){salary=s;}else{cout<<"错误:工资不能为负数!"<<endl;}}};intmain(){//使用带参构造函数创建员工对象Employeeemp1("张伟","软件工程师",8500.50);Employeeemp2("李娜","项目经理",12000.0);//使用默认构造函数Employeeemp3;cout<<"===员工信息==="<<endl;emp1.displayInfo();cout<<"------------------"<<endl;emp2.displayInfo();cout<<"------------------"<<endl;emp3.displayInfo();//演示修改信息cout<<"\n---修改emp3的信息---"<<endl;emp3=Employee("王强","实习生",3000.0);emp3.displayInfo();return0;}定义一个名为Book的结构体,包含书名、作者和价格(分别为字符串和浮点数)。编写一个程序,创建一个结构数组存储多本书的信息,并实现搜索功能,根据书名查找书籍。#include<iostream>#include<string>#include<vector>#include<algorithm>//用于transform(可选,用于忽略大小写)usingnamespacestd;//定义Book结构体structBook{stringtitle;//书名stringauthor;//作者doubleprice;//价格};//按书名精确查找(区分大小写)intfindBookByTitle(constvector<Book>&books,conststring&target){for(size_ti=0;i<books.size();++i){if(books[i].title==target){returnstatic_cast<int>(i);//返回索引}}return-1;//未找到}//按书名模糊查找(不区分大小写,包含子串)vector<int>findBooksByTitlePartial(constvector<Book>&books,conststring&keyword){vector<int>indices;stringlowerKeyword=keyword;transform(lowerKeyword.begin(),lowerKeyword.end(),lowerKeyword.begin(),::tolower);for(size_ti=0;i<books.size();++i){stringlowerTitle=books[i].title;transform(lowerTitle.begin(),lowerTitle.end(),lowerTitle.begin(),::tolower);if(lowerTitle.find(lowerKeyword)!=string::npos){indices.push_back(static_cast<int>(i));}}returnindices;}//打印单本书信息voidprintBook(constBook&book){cout<<"书名:"<<book.title<<"\n作者:"<<book.author<<"\n价格:$"<<book.price<<endl;}intmain(){//初始化结构数组(使用vector更灵活)vector<Book>library={{"C++Primer","StanleyB.Lippman",59.99},{"TheCProgrammingLanguage","BrianW.Kernighan",45.50},{"EffectiveC++","ScottMeyers",49.99},{"Java核心技术","CayS.Horstmann",89.00},{"Python编程:从入门到实践","EricMatthes",79.80}};cout<<"===图书馆藏书列表==="<<endl;for(size_ti=0;i<library.size();++i){cout<<"["<<i+1<<"]";printBook(library[i]);cout<<"------------------------"<<endl;}//精确搜索stringsearchTitle;cout<<"\n请输入要精确查找的书名:";getline(cin,searchTitle);intindex=findBookByTitle(library,searchTitle);if(index!=-1){cout<<"\n找到书籍:"<<endl;printBook(library[index]);}else{cout<<"\n未找到书名完全匹配的书籍。"<<endl;//尝试模糊搜索cout<<"\n正在尝试模糊搜索(不区分大小写,包含关键词)..."<<endl;vector<int>matches=findBooksByTitlePartial(library,searchTitle);if(!matches.empty()){cout<<"🔍找到以下可能匹配的书籍:"<<endl;for(intidx:matches){cout<<"--------------------"<<endl;printBook(library[idx]);}}else{cout<<"未找到任何包含\""<<searchTitle<<"\"的书籍。"<<endl;}}return0;}定义一个类Matrix,包含一个二维数组作为私有成员。提供成员函数进行矩阵加法和乘法运算。编写主函数,测试这些矩阵操作功能。#include<iostream>#include<vector>#include<stdexcept>usingnamespacestd;classMatrix{private:vector<vector<double>>data;introws;intcols;public://构造函数:创建rows×cols的矩阵,初始化为0Matrix(intr,intc):rows(r),cols(c){if(r<=0||c<=0){throwinvalid_argument("矩阵行列数必须为正整数");}data.resize(rows,vector<double>(cols,0.0));}//通过initializer_list支持初始化(C++11)Matrix(initializer_list<initializer_list<double>>list){rows=list.size();if(rows==0){cols=0;return;}cols=(*list.begin()).size();data.resize(rows,vector<double>(cols));inti=0;for(auto&row:list){if(row.size()!=static_cast<size_t>(cols)){throwinvalid_argument("每行元素个数必须一致");}intj=0;for(auto&val:row){data[i][j++]=val;}i++;}}//获取行数和列数intgetRows()const{returnrows;}intgetCols()const{returncols;}//设置和获取元素(带边界检查)voidsetElement(inti,intj,doublevalue){if(i<0||i>=rows||j<0||j>=cols){throwout_of_range("矩阵索引越界");}data[i][j]=value;}doublegetElement(inti,intj)const{if(i<0||i>=rows||j<0||j>=cols){throwout_of_range("矩阵索引越界");}returndata[i][j];}//矩阵加法:要求两个矩阵同维Matrixadd(constMatrix&other)const{if(rows!=other.rows||cols!=other.cols){throwinvalid_argument("矩阵加法:维度不匹配");}Matrixresult(rows,cols);for(inti=0;i<rows;++i){for(intj=0;j<cols;++j){result.data[i][j]=data[i][j]+other.data[i][j];}}returnresult;}//矩阵乘法:A(m×n)*B(n×p)=C(m×p)Matrixmultiply(constMatrix&other)const{if(cols!=other.rows){throwinvalid_argument("矩阵乘法:列数与行数不匹配");}Matrixresult(rows,other.cols);for(inti=0;i<rows;++i){for(intj=0;j<other.cols;++j){doublesum=0.0;for(intk=0;k<cols;++k){sum+=data[i][k]*other.data[k][j];}result.data[i][j]=sum;}}returnresult;}//重载+运算符(可选,增强易用性)Matrixoperator+(constMatrix&other)const{returnadd(other);}//重载*运算符(可选)Matrixoperator*(constMatrix&other)const{returnmultiply(other);}//打印矩阵voidprint()const{for(inti=0;i<rows;++i){for(intj=0;j<cols;++j){cout<<data[i][j]<<"\t";}cout<<endl;}}};intmain(){try{//方法1:使用initializer_list初始化cout<<"===矩阵A==="<<endl;MatrixA={{1,2,3},{4,5,6}};A.print();cout<<"\n===矩阵B==="<<endl;MatrixB={{7,8,9},{10,11,12}};B.print();//矩阵加法cout<<"\n===A+B==="<<endl;MatrixC=A.add(B);C.print();//方法2:动态创建矩阵并赋值cout<<"\n===矩阵D(2x3)==="<<endl;MatrixD(2,3);D.setElement(0,0,1);D.setElement(0,1,0);D.setElement(0,2,2);D.setElement(1,0,-1);D.setElement(1,1,3);D.setElement(1,2,1);D.print();cout<<"\n===矩阵E(3x2)==="<<endl;MatrixE(3,2);E.setElement(0,0,3);E.setElement(0,1,1);E.setElement(1,0,2);E.setElement(1,1,1);E.setElement(2,0,1);E.setElement(2,1,0);E.print();//矩阵乘法cout<<"\n===D*E(2x2)==="<<endl;MatrixF=D.multiply(E);F.print();//使用运算符重载(更简洁)cout<<"\n===使用运算符重载:A+B==="<<endl;(A+B).print();cout<<"\n===使用运算符重载:D*E==="<<endl;(D*E).print();}catch(constexception&e){cerr<<"错误:"<<e.what()<<endl;return1;}return0;}13.定义一个枚举类型VehicleType,包含汽车、卡车、摩托车等类型。定义一个类Vehicle,包含车辆类型、品牌和颜色(均为字符串)。编写一个程序,根据用户输入的类型动态创建不同的Vehicle实例,并显示其信息。#include<iostream>#include<string>#include<vector>usingnamespacestd;//定义枚举类型VehicleTypeenumclassVehicleType{CAR,//汽车TRUCK,//卡车MOTORCYCLE//摩托车};//将枚举值转换为字符串(用于显示)stringvehicleTypeToString(VehicleTypetype){switch(type){caseVehicleType::C

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论