版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
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(chǎn)’;
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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025版醫(yī)藥企業(yè)藥品市場營銷推廣合同范本3篇
- 醫(yī)院通信光纜敷設合同
- 智能教育清運施工合同
- 沿海公路擴建項目合同
- 包裝加工工程安裝施工承包合同
- 電力工程委托策劃合同模板
- 家具制造招投標注意事項
- 2025版能源行業(yè)勞動合同安全生產(chǎn)與應急管理合同3篇
- 2024年物流園區(qū)停車場運營管理承包合同范本3篇
- 2024年牙科醫(yī)療器械公司與制造商關于義齒加工的合同
- 房地產(chǎn) -建筑安裝工程工期定額文件(2023版)
- GJB《質(zhì)量分析報告》模板
- GB/T 27030-2006合格評定第三方符合性標志的通用要求
- GB/T 17271-1998集裝箱運輸術語
- GB/T 13738.1-2008紅茶第1部分:紅碎茶
- 氟化工藝課件
- 技術部經(jīng)理助理崗位職責(2篇)
- 三年級上冊數(shù)學教案-3.1 時間的初步認識三(年 月 日-復習課)▏滬教版
- 急診科診療常規(guī)
- 員工獎懲簽認單
- 檢驗檢測服務公司市場研究與市場營銷方案
評論
0/150
提交評論