版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 消防設(shè)施維護(hù)合同三篇
- 網(wǎng)絡(luò)營(yíng)銷(xiāo)勞動(dòng)合同三篇
- 高速公路貨物運(yùn)輸合同三篇
- 汽車(chē)行業(yè)發(fā)展咨詢(xún)觀察
- 營(yíng)銷(xiāo)行業(yè)安全管理工作總結(jié)
- 2001年河南高考化學(xué)真題及答案(圖片版)
- DB32∕T 3512-2019 公路協(xié)同巡查管理系統(tǒng)建設(shè)技術(shù)規(guī)范
- 2024年美術(shù)教案范例
- 農(nóng)田水利工程招標(biāo)合同(2篇)
- 【部編版九下歷史】知識(shí)清單
- 三年級(jí)上冊(cè)數(shù)學(xué)教案-3.1 時(shí)間的初步認(rèn)識(shí)三(年 月 日-復(fù)習(xí)課)▏滬教版
- 員工獎(jiǎng)懲簽認(rèn)單
- 檢驗(yàn)檢測(cè)服務(wù)公司市場(chǎng)研究與市場(chǎng)營(yíng)銷(xiāo)方案
- VDA270氣味性測(cè)試參考標(biāo)準(zhǔn)中文
- 水泥穩(wěn)定碎石基層及底基層檢驗(yàn)批質(zhì)量檢驗(yàn)記錄
- 2022年版課程方案解讀及學(xué)習(xí)心得體會(huì):課程的綜合性與實(shí)踐性
- 2737市場(chǎng)調(diào)查與商情預(yù)測(cè)-國(guó)家開(kāi)放大學(xué)2018年1月至2021年7月期末考試真題及答案(201801-202107不少于6套)
- 跨國(guó)公司財(cái)務(wù)管理課后習(xí)題答案
- 公園對(duì)地價(jià)和環(huán)境的影響
- 新會(huì)計(jì)準(zhǔn)則財(cái)務(wù)報(bào)表模板(帶公式)
- 建模案例—飛行管理問(wèn)題
評(píng)論
0/150
提交評(píng)論