版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
ObjectivesTobeabletoconstructasimpleC++programTo
beabletobefamiliarwithinput/outputstreamToknowhowtouseC++constantsTounderstandhowtoconstructprogramsmodularlybyusingfunctions(data
abstraction)01C++ProgramStructure03Constants02Input/OutputStream04Functions01C++ProgramStructureABriefDescriptionofC++C++isageneral-purposeprogramminglanguagewithadvantagestowardsthesystemprogrammingthatisabetterCsupportsdataabstractionsupportsstructuredprogrammingsupportsobject-orientedprogrammingsupportsgenericprogrammingC++ProgramStructureProblem:Writeaprogramforagradebookofagivencourse.Thegradebookincludescourse’sname,hourandlecturer,aswellasstudent’sID,nameandgradeInputallinformationoncourseandstudent;Calculatetheaveragegradeofthecourse;Printthegradebook.CaseStudy1Requirements:C++ProgramStructureDataToacourse,name,hourandlecturer,averagegrade;Tomanystudents,ID,nameandgrade;2.Datatypesname,lecturer-string(char*),grade-int,average-float3.Outputagradebookhavingacoursename,hourandlecturer,manystudents’ID,nameandgrade,
and
course
average
grade.4.Procedures(algorithm)InputalldataincludeacourseandstudentsCalculateaveragegradePrintagradebookProblem-solvingIDNameGrade200405XXXwang89………average70.67Name:OOPHour:48Lecturer:LIUJMGradeBookofOOPC++ProgramStructuremainsetCoursesetStudentaverageGradeprintCourseprintStudentGradeprintGradeBookinputStructuredprogrammingC++ProgramStructure////////////////////////////////////////////////////////////////////////gradebook.cpp//Theprogramreadscourseinformationandstudents'gradefromthe//console,calculatestheaveragegradeandoutputsstudents'grades.//////////////////////////////////////////////////////////////////////#include
<iostream>#include
<string>#include
<iomanip>using
namespacestd;//declarationofconstantsconst
intstudentNum=5;//declarationofinputfunctionsvoidsetCourseInfo(string&cName,string&lectName,int&cHour);voidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],
int(&g)[studentNum]);doubleaverage(int
g[]);//declarationofoutputfunctionsvoidprintCourseInfor(string,string,int);voidprintGradeBook(int*,string*,int*);intmain(){stringcourseName;stringlecturer;intcourseHour;intstudentNo[studentNum];stringstudentName[studentNum];intgrade[studentNum];//ReadthecourseandstudentdatasetCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);//DisplaythecourseandstudentdataprintCourseInfor(courseName,lecturer,courseHour);printGradeBook(studentNo,studentName,grade);return0;}C++ProgramStructuredoubleaverage(int
g[]){intsum=0;for(inti=0;i<studentNum;i++) sum+=g[i];return
static_cast<double>(sum)/studentNum;}C++ProgramStructure//ReadthecourseandstudentdatavoidsetCourseInfo(string&cName,string&lectName,int&cHour){cout<<"EntercourseInformation\n";cin>>cName>>lectName>>cHour;}voidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],
int(&g)[studentNum]){cout<<"Enterstudent'sgrades\n";for(inti=0;i<studentNum;i++){sNo[i]=i;cin>>sName[i]>>g[i];}}C++ProgramStructurevoidprintCourseInfor(string
cName,string
lectName,int
cHour){cout<<"Coursename:"<<cName
<<"Coursehour:"<<cHour
<<"Lecturer:"<<lectName<<endl;}voidprintGradeBook(int*sNo,string*sName,int*sg){cout<<"----------------------------\n";cout<<"StudentNoNameGrade\n";for(inti=0;i<studentNum;i++)cout<<setw(9)<<right<<sNo[i]<<setw(10)<<sName[i]<<setw(7)<<right<<sg[i]<<endl;cout<<"----------------------------\n";cout<<"Theaveragegrade:"<<average(sg)<<endl;}C++ProgramStructureAcommonstructureofsimple,onefile,C++programsCommentsdescribe
theprogram,name,…Includestatementsspecifytheheaderfilesforlibraries.//gradebook.cpp//Theprogramreadscourseinformation…Usingnamespacestatement.#include<iostream>usingnamespacestd;LinecommentsBlockcommentsGlobaldeclarations(consts,types,variables,...).const
intstudenNum=5;Functionprototypes(declarations)voidprintGradeBook(int*,string*,int*);The
mainfunctiondefinitionintmain(){stringcourseName;stringlecturer;intcourseHour;intstudentNo[studentNum];stringstudentName[studentNum];intgrade[studentNum];//ReadthecourseandstudentdatasetCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);……}C++ProgramStructureFunctiondefinitionsdoubleaverage(int
g[]){intsum=0;for(inti=0;i<studentNum;i++) sum+=g[i];return
static_cast<double>(sum)/studentNum;}02Input/Output
Stream//ReadthestudentdatavoidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],
int(&g)[studentNum]){cout<<"Enterstudent'sgrades\n";for(inti=0;i<studentNum;i++){sNo[i]=i;cin>>sName[i]>>g[i];}}Input/OutputStreamOutputstreamInputstreamTheiostreamlibrarydefinesinput/outputforeverybuilt-intype.#include<iostream>Input/OutputStreamAstream
isasequenceofcharactersfromthesourcetothedestination.Therearetwotypesofstreams:Inputstream:Asequenceofcharactersfromaninputdevice(keyboard)tothecomputer(variables).Outputstream:Asequenceofcharactersfromthecomputer(variables)toanoutputdevice(screen).Input/OutputStreamTheextractionoperator(>>)isusedasaninputoperator.Inputstreamisfromthedevicetovariables.Keyword
cinisthestandardinputstream.Theinsertionoperator(<<)isusedasoutputoperator.Outputstreamisfromvariablestothedevice.Keyword
coutisthestandardoutputstream.cin>>courseName>>courseHour>>lecturer;
cout<<“Coursename:“<<courseName<<endl;ConsoleinputConsoleoutput//ReadthestudentdatavoidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],int(&g)[studentNum]){cout<<"Enterstudent'sgrades\n";for(inti=0;i<studentNum;i++){sNo[i]=i;cin>>sName[i]>>g[i];}}Input/OutputstreamOutputstream(printf)Inputstream(scanf)03ConstantsConstantsTheconst
keywordmeansthatavaluedoesnotchangedirectly.Aconstantmustbeinitialized.#include
<iostream>#include
<string>#include
<iomanip>using
namespacestd;//declarationofconstantsconst
intstudentNum=5;A#defineisamacrowhichreplacesthemacro-namewithauser-definedtextstatement.Aconstidentifierallowsavariabletobeconstantthroughoutthefile.Constantsconstintmodel=90;constintv[]={1,2,3,4};constintx;intmain(){model=200;v[2]++;}Example//error–cannotbechanged//error–cannotbechanged//error-don’tinitializevoidf(){charstr[]="hello";char*str1=str;const
char*p1=str;//valueisconstant//p1[2]='w';//errorp1=str1;char*constp2=str;//addressisconstantp2[2]='w';//p2=str1;//errorconst
char*constp3=str;//p3[2]='w';//error//p3=str1;//error}04FunctionsFunctionsintmain(){stringcourseName;stringlecturer;intcourseHour;intstudentNo[studentNum];stringstudentName[studentNum];intgrade[studentNum];//ReadthecourseandstudentdatasetCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);//DisplaythecourseandstudentdataprintCourseInfor(courseName,lecturer,courseHour);printGradeBook(studentNo,studentName,grade);return0;}Functions:programisbrief.easilymaintainenhancetheefficiencyofprogrammingreusableWhytousefunctions?Thefunctionalfeaturesofaprogramcanbesubdividedintoblocksofcodeknownas
functions.intmain(){…….setCourseInfo(courseName,lecturer,courseHour);}voidsetCourseInfo(string&cName,string&lectName,int&cHour){cout<<"EntercourseInformation\n";cin>>cName>>lectName>>cHour;}voidsetCourseInfo(string&cName,string&lectName,int&cHour);DeclarationandDefinitionofFunctionsAdeclarationestablishesthenameofthefunction,thetypeofreturnedbythefunction,theparameternumbersandtypesoftheparameterlist.declaration-prototypeFunctionbodyFunctiondefinitionFunctioncallHowtousefunctions?FunctionsignatureFunctionheaderFunctionswithDefaultArguments/ParametersProblem:Inquireastudent’sgradeinwhichispassorfail.intmain(){setCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);inttempNo;cout<<"Inquireastudent'sgrade.EnterastudentID\n";cin>>tempNo;cout<<gradeResult(grade[tempNo])<<endl;return0;}chargradeResult(int,int=60);DefaultparameterchargradeResult(int
gradeOne,int
passValue){if(gradeOne>=passValue) return
'P';else return
'F';}DefaultargumentCaseStudy1-1FunctionswithDefaultParametersA
defaultparameterisafunctionparameter
thathasadefaultvalueprovidedtoit.chargradeResult(int,int=60);Adefaultparameteristypecheckedatthe
timeofthefunctiondeclarationandevaluatedatthetimeofthecall.(1)Iftheuserdoesnotsupplyavalueforthisparameter,thedefaultvaluewillbeused;(2)Iftheuserdoessupplyavalueforthedefaultparameter,theuser-suppliedvalueisusedinsteadofthedefaultvalue.FunctionswithDefaultParametersvoidprint(intval1=10,intval2=20,intval3=30);intmain(){print();print(31);print(31,10);print(31,16,15);}voidprint(intval1,intval2,intval3){cout<<val1<<val2<<val3<<endl;}Result:102030312030311030311615definitionFunctioncallWhentherecanexistmorethanoneparameterintheparameterlist,forexample,declarationLeftmostcriteria:fromlefttorightFunctionswithDefaultParametersvoidprint(intval1=10,intval2=20,intval3);voidprint(intval1=10,intval2,intval3=30);
voidprint(intval1,intval2=0,intval3=0);//error//error//okAlldefaultparameterswithindeclarationordefinitionmustbetherightmostparameters.Rightmostcriteria:fromrighttoleftFunction
OverloadingProblem:OutputthegradebookwithstudentIDandgrade.Twoormorefunctionshavethesamenameinthesamescopeiscalledfunctionoverloading.voidprintGradeBook(int*sNo,string*sName,int*sg);voidprintGradeBook(intsNo[],intg[]);C++allowsyoutospecifytwoormoredefinitionsfora
function
name
inthesamescope.Thecompilerwillneedtodeterminewhichfunctiontoexecutebasedonthefunctionsignature.Howtodo?CaseStudy1-2Function
OverloadingvoidprintGradeBook(int
sNo[],int
g[]){cout<<"----------------------------\n";cout<<"StudentNoGrade\n";for(inti=0;i<studentNum;i++) cout<<sNo[i]<<g[i]<<endl;cout<<"----------------------------\n";cout<<"Theaveragegrade:"<<average(g)<<endl;}voidprintGradeBook(int*sNo,string*sName,int*sg){cout<<"----------------------------\n";cout<<"StudentNoNameGrade\n";for(inti=0;i<studentNum;i++) cout<<sNo[i]<<sName[i]<<sg[i]<<endl;cout<<"----------------------------\n";cout<<"Theaveragegrade:"<<average(sg)<<endl;}printGradeBook(studentNo,grade);printGradeBook(studentNo,studentName,grade);voidprintGradeBook(int*sNo,string*sName,int*sg);voidprintGradeBook(intsNo[],intg[]);Whenyoudefineoverloadedfunctions,youmustprovideaparameterlistwithdifferentparameters.Function
Overloading-HowtoCallanOverloadedFunctionMakingacalltoanoverloadingfunctionresultsinoneofthethreepossibleoutcomes:AmatchisfoundNomatchisfoundAnambiguousmatchisfoundFunction
Overloading–HowtoCallanOverloadedFunctionTrytofindanexactmatchTrytofindamatchthroughpromotions
booltoint
chartoint
e.g.charc=‘a’;
shorttoint
floattodoubleTrytofindamatchthroughstandardconversions
inttodouble
doubletointe.g.doublea=3.4;intn=(int)a;
doubletolongdoubleT*tovoid*
derived*toBase*
inttounsigned
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 浴珠珠状沐浴剂市场发展预测和趋势分析
- 2024年度供应链管理及服务合同
- 2024年度技术研发保密录像合同范本
- 2024年度游戏开发合同游戏设计要求
- 2024年度巢湖劳动合同续签申请书指南
- 2024年度宠物店品牌合作合同:宠物店与其他品牌之间的合作推广协议
- 2024年度建筑工程施工合同标的及工程描述
- 2024年度人力资源外包合同:保安人员派遣服务协议
- 羽毛掸市场需求与消费特点分析
- 2024年度健身俱乐部会员合同:关于健身俱乐部与会员之间的服务内容、费用等规定
- 购买文件登记表.doc
- 弧长与扇形的面积教学设计范文
- 人教版小学六年级数学毕业升学试卷(附:试卷命题意图、参考答案及评分标准)
- 安全生产工作汇报材料 (4000字)
- 入团积极分子“推优入团”申请推荐表
- 线性代数在密码学中的应用
- 电力公司司徽、司歌、企业精神试行方案和电力公司安全倡议书汇编
- 燃气公司运行管理制度汇编
- 新教科版五年级科学上册4-1《我们的身体》PPT课件
- 高速公路开口及交通施工方案
- 安全小故事(完整版)
评论
0/150
提交评论