C++实验指导手册_第1页
C++实验指导手册_第2页
C++实验指导手册_第3页
C++实验指导手册_第4页
已阅读5页,还剩125页未读 继续免费阅读

下载本文档

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

文档简介

C++实验指导手册实验一熟悉实验环境ー、实验目的了解和使用VC集成开发环境,熟悉VC环境的基本命令和功能键;熟悉常用的功能菜单命令,学习使用VC++环境的帮助;了解用VisualC++开发C++应用程序的过程,二、实验内容.熟悉VisualC++实验环境[实验步骤](1)启动DeveloperStudio,看看初始化界面由哪些部分组成(2)查看各菜单项,看看都有哪些子菜单和命令(3)将鼠标放置于各工具条图标上,系统会自动显示该图标代表的命令含义,了解一下都有哪些命令。(4)在任意工具条上单击鼠标右键,弹出式菜单上将显示所有可用的工具条,选择其中没有对号(ノ)的项,看看有什么效果,再选择有对号的项,又有什么效果?(5)将鼠标移动到任意工具条上,将鼠标放到图标间隙,按下鼠标左键不放,移动鼠标到屏幕中间,有什么现象发生?再将它拖回到原来位置,有什么现象发生?(6)将鼠标移动到左边的工作区窗口,按下鼠标左键不放,移动鼠标到屏幕中间,有什么现象发生?再将它拖回到原来位置,有什么现象发生?7)将鼠标移动到下边的输出窗口,按鼠标右键,弹出ー个菜单,选择其中的菜单项"Hide”,结果如何?耍重新显示该窗口,选择菜单View〔Output,窗口是不是又显示出来了?(8)学习使用帮助系统。如果你用的是VisualC++5.0,则在工作区窗口的InfoView中选择你感兴趣的内容,双击它,在文档区显示具体的帮助信息。如果你用的是VisuaIC++6.0,选择菜单HelpContents,启动MSDN联机帮助系统,学习使用该帮助系统。联机帮助系统是ー个相对独立的程序,它和DeveloperStudio是两个程序,但是它的启动和停止都受DeveloperStudio影响。MSDN联机帮助系统运行的前提条件是DeveloperStudio在运行。(9)选File|Exit退出DeveloperStudio«.控制台应用程序用AppWizard建立一个控制台应用,在终端上输出"Hello”。术语:“控制台应用程序”是ー个在DOS窗口中运行的基于字符的程序。由于这种模式的应用程序比Windows程序简单,我们先选择利用VisualC++来建立这样ー个应用,这样使得我们可以将精力先投入到学习使用C++编程语言,而不需要把过多的精力投入到学习复杂的Windows编程中去。[实验步骤]1)创建第一个应用首先创建一个项目(project),项ロ将代表你的应用,存放你应用的所有信息,包括源文件、资源文件、编译连接设置等。创建项目的步骤为:(1)启动DeveloperStudio(2)从主菜单中选择FileINew,将显示出New对话框(3)选择Projects标签,并从列表中单击Win32ConsoleApplication(4)在‘'Location”编辑框中输入你的工作目录名称,如c:\student\your_name(自建吧)(5)在对话框的右上角的“projectname”编辑框内键入项目的名字,如"Hello",系统将自动为你的项目分配ー个默认的目录(6)单击0K继续(7)如果是VC6.0,系统将显示ー个询问项目类型的程序向导,选择"anemptyprojectM(8)单击Finish或OK结束配置,创建应用程序这时系统为你创建一个新的项目,并且在左边的工作区窗口中将出现你项目的名字。エ作区窗口除原来的InfoView标签外又增加了两个标签(如果是VisualC++6.0,则没有InfoView标签):ClassView和FileView。ClassView从类的角度显示项目中建立的各个类,双击某个类名將会在右边的文档显示区显示类的定义文件并把文件的当前位置定位到所选的类;FileView显示构成项目的各个文件,选择某一文件将会在右边的文档显示区显示文件内容;InfoView是VC5的帮助文件目录,在这里可以选择所要获取帮助的标题,在右边将显示帮助内容。2)编辑你的第一个C++源程序用下面的方法在你创建的项目中添加一个文件:(1)在主菜单上选择File|New(2)在New对话框中选择File标签,单击“C++SourceFile”(3)选中AddtoProject复选框(4)在右边的Filename编辑框中为文件指定一个名字,如Hello,系统将自动为你加上后缀.cpp。新的空白文件将自动打开,显示在文档显示区。在文件中输入以下内容(不包括上下两条横线)://helloworldexample#include<iostream.h>intmainO{cout«"hello!"«endl;return〇;//正常返回仔细检查你输入的内容,确保内容正确ー》[常用编辑命令]虽然许多编辑命令可以通过菜单和工具栏实现,但大量的编辑命令都可以通过键盘实现。以下命令通常用键盘实现:・撤消前一次操作。当你进行了一次错误的操作时,可以通过敲击键盘上的Ctrl+Z完成;・重复前一次操作。通过敲击Ctrl+Y实现・剪切一行。用Ctrl+L来删除一行并将它放到剪切板中・剪切。将选中的文本删除并将它放到剪切板中,用Ctrl+X实现・复制。将选中的文本复制到剪切板中,用Ctrl+C实现・粘贴。将剪切板中的内容放到编辑器中文本的当前位置处(由光标指示)。用Ctrl+V实现.要想了解关于键盘操作命令的完整列表,可以选择Help菜单下的KeyboardMap»你没有必要记住所有的命令,有些根本不常用。3)保存你的源文件单击工具栏中的〃save”图标,或者选择File|Save来保存你的文件。C++源文件的扩展名为.cpp。扩展名非常重要,DeveloperStudio根据文件的扩展名来区分文件类型,并且根据文件类型提供相应的编辑帮助(如正确的语法高亮显示)。4)编译、连接得到可执行程序编辑结束后,仔细检查你输入的内容,看有无错误。确认没有错误之后,选择主菜单的BuildBuildHello.exe来编译你的项目(也可以按功能键F7).如果你输入的内容没有错误,那么,在屏幕下方的输出窗口将会显示:hello.exe-0error(s),0warning(s)如果在编译时得到错误或警告,是你的源文件出现错误,再次检查你的源文件,看是否有错误,改正它。5)改正源程序中的错误编译的错误会在DeveloperStudio的下方的输出窗口显示出来,逐个查看这些错误的内容,用鼠标双击,光标可以自动移动到发生错误的源程序的相应地点,仔细检查你的源程序,改正发生错误的地方,注意是否否遗留了分号、引号或括号等。改正后,再重复步骤4)的操作,直到编译连接通过为止。6)运行你的第一个程序你可以有三种方式运行你的程序:・在开发环境中运行程序选择BuiId〔Executehello.exe(或者Ctrl+F5),在开发环境中执行你的程序。程序运行以后将显示一个类似于DOS的窗口,在窗口中输出一行“hello”,紧接着在下面显示“Pressanykeytocontinue",这句话是系统提示你按任意键退出当前运行的程序,冋到开发环境中。按任意键,窗口关闭,退回到VisualC++开发环境。我们实验中将用这种方式运行程序。・在DOS环境ド运行程序打开DOS窗ロ,改变工作路径到项目目录,该目录是你在创建目录时指定的。如果你不记得了,可以在DeveloperStudio中的工作区窗口中选择项目名称(这里是"hellofiles"),然后选择菜单ViewlProperties,将可以显示出项目路径。切换到debug子目录下,运行hello,exe,程序将输出:‘hello'。・在Windows环境下运行程序打开Windows的资源管理器,找到程序所在的目录,运行它。你看到的结果是怎样的?.Windows应用用AppWizard建立一个MFCWindows应用,在窗口中输出"Hello,World!"术语:AppWizard是ー个工具,利用该工具,你可以创建一个建立在MFC基础上的窗口应用程序框架,然后在这个框架中加上自己的应用逻辑。你可以选择所创建的应用类型,最常用的是多文档应用(就象你用的字编辑器MicrosoftWord——样,可以同时打开多个文档窗ロ的应用)、单文档应用(类似于Windows提供的notepad,一次只能打开ー个文档)和对话框应用(类似于Windows的时钟程序)。[实验步骤]1)创建一个新项目利用DeveloperStudio的AppWizard创建一个新的项目,步骤为:(1)选择菜单File|New,系统将显示New对话框(2)选择Projects标签,在显示的项目类型中选择MFCAppWizard(exe)(3)在右边的ProjectName编辑框中输入项目名称,如“helloMFC",然后按OK.(4)MFCAppWizard将分几步询问你有关要建立的新项目的配置。第一个对话框问你是创建哪种类型的应用(单文档、多文档还是对话框类型),选择创建单文档应用“Singledocument",然后按Next按钮(5)翻过后面的五个页面(按Next),每个页面可以让你改变项目的不同选项,这个例子暂时不设置这些选项。(6)最后ー个MFCAppWizard屏幕告诉你AppWizard为你自动产生的类。单击Finish键,AppWizard显示一个关于该项目的摘要,列出这些类和你所选择的特征。如图所示:(7)单击0K,系统自动产生helloMFC所需要的文件。2)浏览helloMFC项目当你用MFCAppWizard创建了helloMFC项目后,这个项目的工作区窗口将会打开,工作区窗口除了原来的InfoView以外(VC5.0),增加了三个标签(如下图):ClassView,ResourceView和FileView,其中ClassView显示工作区中所有项目的类及类的成员:ResourceView显示项目中包含的资源文件;FileView显示项目中的各种文件资源。你可以先选择FileView看一下AppWizard为你创建了哪些文件,然后选择ClassView看-下定义了哪些类。ClassView中还可以看到ー个Globals文件夹,単击它前面的加号,可以看到,有一个预定义的全局变量theApp,这是你的Windows应用程序类的对象。3)编译连接运行按F7或者选择菜单BuiId|BuiIdhelloMFC.exe,编译连接得到可执行程序,再按Ctrl+F5或者选择BuiId〔ExecutehelloMFC.exe运行该程序。程序的结果如下:4)用MFC处理输出现在是你来修改程序的时候了。我们希望在程序中间的窗口上显示一行文字“Hello,World・。如何修改呢?(1)在工作区窗口中选择ClassView标签,単击helloMFCclasses前面的加号(如果已经变成减号则不做此操作)(2)单击类CHelloMFCView类前面的加号(3)双击OnDrawO函数,在右边的文档将显示窗口显示文件helloMFCView的内容,并且自动将光标定位到函数OnDrawO处。(4)修改OnDraw函数的定义,在最后一行加一句:pDC->TextOut(50,50,"Hello,World");(5)按Ctrl+s或者选菜单File|Save来保存所作的修改5)编译连接并运行重新编译连接该项目,运行程序,你可以用Ctrl+F5直接运行程序,系统将询问你是否重新编译该项目,回答“是(Yes)”,如果有编译错误,仔细检查你加的一句话,是否有错。当编译连接通过后,系统会自动运行该程序。结果与上面有什么不同?经过上述修改后,程序可以输出一行文字“Hello,World"«匹.无标题匹.无标题ーCl文件⑹编督(©查看&)帮助时0け0Ix与e昌jHello,World就绪 I~対!~/4.编写简单的计算程序输入圆的半径,计算圆的周长和面积并输出。[测试数据]输入:2输出:Theperimeterofthecircle:12.5664Theareaofthecircle:12.5664输入:10输出:Theperimeterofthecircle:62.8318Theareaofthecircle:314.159[实验步骤]1)创建一个控制台项目选择菜单File|New,在Projects标签下选择Windows32ConsoleApplication,输入项目名称“circle”,然后按0K2)在项目中增加一个文件选择菜单FilelNew,在Files标签下选择C/C++SourceFile,输入文件名称"circle",然后按0K3)在文件中输入以下内容〃该程序让用户输入圆的半径Radius,输出圆的周长Perimeter和面积Area#include<iostream.h>#include<math.h>constdoublePI=3.14159I〃定义ー个常量PIintmain(){intradius;doubleperimeter,area;cout«”Pleaseinputtheradius:";cin»radius;perimeter=2*PI*radius;//周长=2nRarea=PI*power(radius,2);〃面积=に!^2cout«"Theperimeterofthecircle:"«perimeter«endl;cout«"Theareaofthecircle:"«area«endl;return0;)注:power(radius,2)表示求radius的平方,power(x,y)是系统预定义的函数,该函数计算x的y次方。该函数的原型在文件math,h中说明。4)编译、连接并运行程序如果你输入的程序有误,用下面的方法定位并修改错误。直到编译连接通过。运行程序,测试数据。ー》[编译和连接错误定位]开发环境下方的输出窗口(Output)显示编译和连接过程中出现的错误,错误信息包括:错误出现的文件名、行号、错误代码。如果不懂错误消息,将光标移动到该错误信息,按F1,就可以显示该错误的帮助信息。在output窗口,双击错误或者选择该错误再按ENTER键,系统自动将光标移动到发生错误的源程序行,你然后就可以改正错误。F4健可以选择并定位下ー个错误[思考问题](1)程序中为什么要将头文件math,h包含进来?(2)建立控制台应用程序的通用步骤是怎样的?实验二简单的C++程序ー、实验目的.进ー步熟悉VC集成开发环境,常用的功能菜单命令;.练习使用C++语法,学习使用VC++基本语句;.编写调试简单C++程序的能力,提高对简单程序的调试能力。二、实验内容.询レ式本早ProgrammingExample;.编程实现并调试本章ProgrammingProblems3,4题。三、实验要求.掌握C++基本语法,如:变量的定义,数据输出:.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果:.提交实验报告四、注意中英文人名的构成差异。实验三C++数据类型、基本I/Oー、实验目的.熟悉VC++数据类型,类型转换,表达式,函数的作用和分类;.练习使用常用数据类型,表达式,学习使用简单的函数;.练习C++格式化输出的相关函数、字符串操作函数。二、实验内容.有关表达式的例题测试,深入理解个中运算符的优先级、运算规则:.调试本章ProgrammingExample质押贷款中的每月还款数额(按月等额还款);.编程实现并调试本章ProgrammingProblems2,4,5题。三、实验要求.复习C++数据类型,运算符,表达式,函数的作用以及数据输出的格式控制符;.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果:四、注意英美钱币知识ProgrammingWarm-upExercise3.质押贷款中的每月还款数额计算公式。附:1源代码:I/*******************************************★*★*★**★***★//Thisprogramcomputesandoutputsthevolumeofacone〃********************************************************#include<iostream>#include<cmath>constdoublepi=3.14;usingnamespacestd;intmain()(doubleRadius=6.4,Height=9;doublevolume; //Definetheneededconstnumbersandvariablesvolume=float(pi)/3*Radius*Radius*Height;//Theformulacout«*'Thecone'svolumeis:"«volume«endl;//Outputcone'svolumereturn0;}2源代码:#include<iostream>#include<cmath>usingnamespacestd;intmain()(constintx1=100,x2=200,x3=300,x4=400;//Definefourintegervaluesinti,n=4;doublemean,s,s1;//Computethemeanmean=(x1+x2+x3+x4)/n;s1=(x1-mean)*(x1-mean)+(x2-mean)*(x2-mean)+(x3-mean)*(x3-mean)+(x4-mean)*(x4-mean)://Theformulaforthestandarddeviations=sqrt(double(s1/(n-1)));//Outputtheresultcout«"Themeanofthefournumbersis:"«mean«endl«"Thestandarddeviationis:"«s«endl;return0;}3源代码:#include<iostream>#include<cmath>doublefun(intn);intfac(intn);usingnamespacestd;intmain(){constintn1=15;cout«Mthefactorialof15directlyis:H«fac(n1)«endl«nthefactorialof15usingstring'sformularis:M«fun(n1)«endl;return0;)doublefun(intn){constdoublepi=3.14;doublep;p=exp(-n)*pow(n,n)*sqrt(2*pi*n);returnp;}intfac(intn){inti;intfac=1;for(i=2;i<=15;i++)fac=fac*i;returnfac;}4源代码:#include<iostream>#include<cmath>#include<iomanip>usingnamespacestd;doublefun(intn);intmain()(doubleN;constintn1=18,n2=3;N=double(fun(n1))/(fun(n2)*fun(n1-n2));cout«"theresultis"<<setw(6)«setprecision(3)«N<<endl;return0;}doublefun(intn){constdoublepi=3.14;doublep;p=double(exp(-n))*pow(n,n)*sqrt(2*pi*n);returnp;}5源代码:#include<iostream>#include<string>usingnamespacestd;voidmain(){stringfullname;stringfirstname;stringmiddlename;

stringlastname;stringstr2;string::size_typestartpos;string::size_typesecondpos;string::size_typeten;string::size_typelength;cout«HPleaseinputafullname:*';getline(cin,fullname);startpos=fullname.find("");firstname=fullname.substr(0,startpos);len=firstname.length():length=fullname.length();str2=fullname.substr(len+1,length-len);secondpos=str2.find("*');middlename=str2.substr(0,secondpos);len=middlename.length()+len;lastname=fullname.substr(len+2,length);cout«*'Firstname:M«firstname«endl;andlastnamecout«"Middlename:,'«middlename«endl;cout«nLastname:H«lastname«endl;}//ThepositionofthefirstH"//Thepositionofthesecond//ThepositionofthefirstH"//ThepositionofthesecondM"//Thelengthofthefullname//Getthefullname//Findthefirstname//Findthesecondname//Findthelastname//Outputfirstname,secondnameー、实验目的.熟悉C++通过iostream输入数据的原理和方法,掌握数据提取符cin的用法;.掌握文件读写操作的原理步骤和注意事项,熟练文件读写操作的编程实现:.掌握基于函数分解的解决问题(编程)方法。二、实验内容.调试本早ProgrammingExample;.编程实现并调试本章ProgrammingProblems2,3,4题。三、实验要求.掌握cin、cout基本语法和用法;.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果;四、注意:1.通过iostream实现数据输入的原理和基本步骤,以及需要定义的变量。附:4.2源代码:附:4.2源代码:#include<iostream>#include<cmath>usingnamespacestd;intmain()#include<fstream>#include<iostream>#include<cmath>#include<iomanip>usingnamespacestd;intmain()(ofstreamoutData;outData.openC^empdata.dar);intj;inti;floatsum=0.0;floataverage;floata[20];floatb[20];cout«"lnput12temperatures:*';for(i=0;i<12;i++){cin»a[i];sum=sum+a[i];average=sum/10;}outData«a[0]«endl;for(i=1;i<12;i++)outData«a[i]«""«a[i]-a[i-1]«endl;//Accessmanipulators//Declareandopenfiles//Declarevariables//Get12temperaturesfromtheuser//Writeoutonfile"tempdata.datMcout<<fixed<<setprecision(2)«"Theaverageis:"//Outputtheaverage«average«endl;outData.close(); //Closefilereturn0;}4.3源代码:#include<iostream>#include<cmath>usingnamespacestd;intmain()intx1,x2,x3,x4;//Definefourintegervaluesinti,n=4;doublemean,s,s1;coutvv”Pleaseinput4intergervalues:*';cin»x1»x2»x3»x4;//Computethemeanmean=(x1+x2+x3+x4)/n;s1=(x1-mean)*(x1-mean)+(x2-mean)*(x2-mean)+(x3-mean)*(x3-mean)+(x4-mean)*(x4-mean);//Theformulaforthestandarddeviations=sqrt(double(s1/(n-1)));//Outputtheresultcout«"Themeanofthefournumbersis:"«mean«endl«"Thestandarddeviationis:"«s«endl;return0;}4.4源代码A:#include<iostream>#include<fstream>#include<string>usingnamespacestd;intmain()(ifstreamindata;stringfilename;cout«"Entertheinputfilename:"«endl;cin»filename;indata.open("filename.c_str()");charch;intflag=0;indata.get(ch);while(ch!='*'){indata.get(ch);if(ch==';)flag=1;if(flag==1){indata.get(ch);while(ch=='')(flag=0;cout«endl;}elsecout«ch;)}indata.close();return0;}4源代码B:〃课本第150页,第4题#include<iostream>#include<fstream>#include<string>usingnamespacestd;intmain(){stringfirst,second,third,filename;ifstreamindata;coutvv”请输入文件名:";cin»filename;indata.open(filename.c_str());indata.ignore(200/,,):indata»first:indata.ignore(200,\'):indata»second;indata.ignore(200,7);indata»third;cout<<first«endl«second«endl«third«endl:indata.close():return0;}实验五选择控制结构ー、实验目的.熟悉VC条件运算符,构造条件表达式;.练习使用If-Then-Else语句;练习使用嵌套的If-Then-Else语句;.跟踪C++程序的运行,提高对程序的调试能力。二、实验内容调试本早ProgrammingExample;2.编程实现并调试本章ProgrammingProblems1,4,7,8选做2-3题onPage196—198。三、实验要求.掌握C++条件运算,会构造C++条件表达式;.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果;四、注意:1.C++程序的调试方法,参见附录5。附:5.1源代码://Sourcecodeof5.1,2007.11.20#include<iostream>usingnamespacestd;intmain(){charch;cout«*'inputaletter:cin»ch;jf(ch=='A,)cout«"Alpha"«endl;if(ch=='B')coutvv”Bravo"vvendl;if(ch==C)cout«,,Charlie,'«endl;if(ch==,D,)cout«',Delta,,«endl;if(ch=='E,)cout«,'Echo',«endl;if(ch=='F')cout«,,Foxtrot"«endl;if(ch==,G,)cout«HGolf"«endl;if(ch==T)cout«',lndia"«endl;if(ch==(J,)cout«,,Juliet,,«endl;if(ch=='K,)cout«MKiloM«endl;jf(ch==L')cout«HLima"«endl;jf(ch=='M')cout«,,Mike,,«endl;if(ch==,N,)cout«',November',«endl;if(ch=='O,)cout«MOscarM«endl;jf(ch==,P')cout«',Papa,,«endl;jf(ch=='Q,)cout«,,Quebec,,«endl;if(ch=='R)cout«"Romeo,,«endl;if(ch==*S,)cout«"Sierra,'«endl;if(ch==T)cout«MTangon«endl;if(ch==,U,)coutvv”Uniform”vvendl;jf(ch==,V,)cout«MVictorM«endl;if(ch==,W,)cout«',Whiskey,,«endl;if(ch==X)cout«',X-ray',«endl;jf(ch==*Y,)cout«,,Yankee',«endl;if(ch==Z)coutvv"Zulu“vvendl;return0;)5.4源代码://Sourcecodeof5.4,2007.11.20#include<iostream>usingnamespacestd;intmain()(intnumberl,number2,number;cout«MThestartdayis(0-6):H;cin»number1;if(number1<0||number1>6)cout«number1«*'isnotbetween0and6"«endl;else{cout«"thedayoftheyear(1-366):H;cin»number2;if(number2<1||number2>366)cout«number2«nisnotbetween1and366"«endl;number=(number1+number2-1)%7;cout«nThedayisif(number==0)cout«nSunday"«endl;if(number==1)cout«HMondayn«endl;if(number==2)cout«',Tuesday',«endl;if(number==3)cout«"Thiresday"«endl;if(number==4)cout«"WednesdayH«endl;if(number==5)cout«,'Friday',«endl;if(number==6)cout«,,Saturday,'«endl;)return0:5.フ源代码:〃5.7题:若干裁判评分程序//Sourcecodeof5.7,2007.11.20#include<iostream>usingnamespacestd;intmain(){inti,j;floats[4],average,min;cout«HEnterfourscores"«endl;for(i=0;i<4;i++){cout«,,s[,,«i«,1]=n;cin»s[i]:while(s[i]<0||s[i]>10)//revised20100328{cout«,,s[',«i«,']isinvalid',«endl;cout«'Inputs["«i«"]again"«endl;cin»s[i];))min=s[0]; 〃可以用ー个循环实现选择最小的值if(min>s[1])min=s[1];if(min>s[2])min=s[2];if(min>s[3])min=s[3];average=(s[0]+s[1]+s[2]+s[3]-min)/3.0;cout«"theoverallscoreis"«average«endl;return0;)8源代码://Sourcecodeof5.8,2007.11.20#include<iostream>#defineN3usingnamespacestd;intmain(){inti,j;floats[N],t;cout«"Enterthescores"«endl;for(i=0;i<N;i++)cin»s[i];for(i=0;i<N-1;i++)for(j=i+1;jvN;j++)if(s[i]<sU]){t=s[i];s[i]=sO];s[j]=t;}cout«"themedianis”«s[(N-1)/2]«endl;return0;}实验六循环控制结构ー、实验目的.熟悉VC循环结构的常用实现语句;.练习使用循环的构造方法:计数型循环(count-conlrolledloops)、事件控制型循环(event-controlledloops)>标志控制型循环(flag-controlledloops)等;.练习嵌套的循环程序。二、实验内容调试本章ProgrammingExample;2.编程实现并调试本章ProgrammingProblems1,2,4,5题。三、实验要求.掌握常用的C++循环构造方法;.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果;四、注意:1.ProgrammingProblems第5题回文的判断,从性能和算法等方面考虑该题目的进ー步改进(后续实验题讨论)。附1.1:ProgrammingProblems第4题源代码A。/*PalindromejudgingProgramusingloopingandcharactercomparing*//*ThisprogramistojudgewhetherastringreadfromcinisastrictPalindrome*//*ProvidedbyMr.CaoZaihui,Nov.2,2007*//・用字符比较的方式判断回文・/#include<iostream>#include<string.h>usingnamespacestd;constintsize=100;intmain()(chara[size];intb; 〃记录字符串的长度intflag=1;cin»a;b=strlen(a); 〃取字符串长度的函数,但是空字符不在其中for(inti=0;i<b/2;i++)(if(a[i]!=a[b-i-l])(flag=O;break;)}if(flag)(cout«HItisaPalindrome!M;}else(cout«nItisNOTaPalindrome!H;)return0;附!.2.ProgrammingProblems第4题源代码B。/*PalindromejudgingProgramusingloopingandcharactercomparing*//*ThisprogramistojudgewhetherastringreadfromcinisastrictPalindrome*//*ProvidedbyMs.LiLi,Nov.22,2007*//・用字符比较的方式判断回文・/usingnamespacestd;intmain()(stringstrl;string::size_typelen;inti,j;cout«nEnterthephrase:n;getline(cin,strl);len=strl.length();i=len-l;j=0;while((j<len)&&(i>=0))if(strl.substr(j,l)=strl.substr(i,l)){j++;i-;}else{cout«str1«endl«uisnotapalindromeH«endl;break;}}if((j==len)&&(i<0))cout«str1«endl«*'isapalindrome.*'«endl;return0;附2:ProgrammingProblems第5题源代码及读取信息的文本文件。/*E-Mailaddressconstructingprogram*//*ProgramtoextractE-Mailaddressesfromafile*//*Bysearchingforcharacter@whichindicatesanE-Mailaddress*//*ByCaoZaihui,Nov.2,2007*/#include<iostream>#include<fstream>#include<string>usingnamespacestd;intmain()(stringal;ifstreaminfile;ofstreamoutfile;infile.open(,,mail.dat,');outfile.openCaddresses.dat");while(!infile){cout«H**canotopeninputfileu«endl;return1;}infile»al;while(infile)(if(al.find(n@M)!=string::npos)//seekfor@trytofindanE-Mailaddressoutfile«a1«endl;infile»al;}infile.close();outfile.close();return0;第5题中获取电子邮件的文本文件(示例文件):|Email.dat-记事本-!□!x|文件⑥编辑@格式9)查看②帮助⑻From:sharon@data:web,13aug200317:12:33edtsubject:re:hito:john@john,daua'semailisdaua_smith@._dtty1,shron附"3:ProgrammingProblems第2题源代码//Sourcecodeof5.8,2007.11.20#include<iostream>#include<fstream>#include<cmath>usingnamespacestd;intmain()(intn=0;floatx,mean,s,sumsqure=0.0,sum=0.0;ifstreaminfile;infile.openC'scores.daf');if(Hnfile){cout«M**Can'topeninputfile.**H«endl;return1:}infile»x;while(infile){sum=sum+x;sumsqure=sumsqure+x*x;n++;infile»x;}mean=sum/n;s=sqrt((n*sumsqure-sum*sum)/(n*(n-1)));cout«*'Themeanis:H«mean«endl«"Thestandarddeviationis:H«s«endl;infile.close();return0;)附4第1题源代码。/20110421//ProgrammingProblemsch06No.l//Programtooutputabarchartofaseriesof24hourlytemperatures.//DesignedbyGaoShudan,April19,2011#include<iostream>#include<fstream>#include<iomanip>#include<cmath>usingnamespacestd;intmain()intj,stars;floattemperature;ifstreaminfile;ofstreamoutfile;infile.open(,,temperatures.dat,');if(!infile)(coutvv”can'topentheinfileH«endl;return1;}outfile.open("output2.dat");if(!outfile)(coutvv”can'topentheoutfilen«endl;return1;)outfile«ntemperaturesfor24hours:u«endl;outfile«setw(6)«"-30M«setw(10)«"0M«setw(10)«,,30,'«setw(10)«,,60,'«setw(10)«n90M«setw(l0)«nl20M«endl;infile»temperature;//Primingreadwhile(infile)(outfile«setw(3)«temperature;if(temperature<0)(stars=int(fabs(temperature/3));for(j=0;j<13-stars;j++)outfilevv'';for(j=0;j<stars;j++)outfile«'**;outfile«endl;)else{for(j=0;j<13;j++)outfile«'';stars=int(temperature/3);for(j=0;j<stars;j++)outfile«endl;)infile»temperature;)cout«"Operaionfinished!M«endl;infile.close();outfile.close();return0;数据文件:输出条形图实验七函数的设计和使用ー、实验目的.熟悉VC函数的结构;.练习使用返回类型为空的函数,练习使用特定返回类型值的函数;.练习用函数编写程序,练习程序多次调用同一个函数。二、实验内容.例(1)交换两个整数的次序后,观察输出结果(函数的传值调用)#include<iostream>usingnamespacestd;voidswap(inta,intb);voidmain()(intx=5,y=7;cout«"x=M«x«"yゴ«y«endl;swap(x,y);cout«"x=M«x«"yゴ«y«endl;}voidswap(inta,intb)(inttemp;temp=a;a=b;b=temp;)例(2)使用函数的引用实现,交换两个整数的次序后,观察输出结果(函数的传址调用)。#include<iostream>usingnamespacestd;voidswap(int&a,int&b);voidmain(){intx=5,y=7;cout«"x=M«x«"yゴ«y«endl;swap(x,y);cout«"x=M«x«"y="«y«endl;}voidswap(int&a,int&b)(inttemp;temp=a;a=b;b=temp;)3.编程实现并调试本章ProgrammingProblems2,4,7题。三、实验要求.掌握常用的C++函数的构造和使用;.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果;附1:ProgrammingProblems第4题源代码及读取信息的文本文件。/*Telephonedirectoryprogramtolookupphonenumbersinafilenumber*//*ByCaoZaihui,Nov.9,2007*/#include<iostream>#include<fstream>#include<string>voidlookup(string,string,char&);usingnamespacestd;main(){stringlast1,first1;charconti;conti='Y';while(conti=='Y,){cout«npleaseinputthefirstandlastname:"«endl;cin»firstl;cin»lastl;lookup(firstlJasti,conti);)return0;)voidlookup(stringfirst!,stringlast1,char&conti){ifstreamindata;indata.open("phonenum.da『');intflag=0;stringnum,first2,last2;while(indata){ indata»first2»last2»num;if(!(pare(first2))&&!(pare(last2))){cout«num«endl;flag=l;))if(flag==O)cout«nthenameisnotinthedirectory"«endl;cout«udoyouwanttolookupanothername:(N/Y)n«endl;cout«upleaseinputYorNH«endl;cin»conti;indata.close();第4题中读取信息所用的文本文件样例:Bphonenum.dat1-Inlxl文件⑥编辑@格式◎查看仪)帮助国)liuwen159638267731zhujun12365487895luyaozaihui45866598555ChrisPeterBphonenum.dat附2:ProgrammingProblems第フ题源代码及输入、输出信息的文本文件。/*Multiple-choiceexamgradingprogram.*//*Thisprogramreadsthekeyandtheanswersfromafile(exams.dat)*//*andoutputtheIDnumbersandscoretoafile(scores.dat)*//*ByCaoZaihui,Nov.9,2007*/#include<iostream>#include<fstream>#include<string>voidcalculate(string,int&,string,string,ofstream&);usingnamespacestd;intmain()(stringID;stringanswer;stringkeys;intscores;ifstreamindata;indata.open("exams.txtM);if(!indata)(cout«',can,topeninputfile.M«endl;returnI;)ofstreamoutdata;outdata.open("scores.txt");if(!outdata){cout«ncan*topenoutputfile."«endl;returnI;}indata»keys;indata»ID»answer;while(indata)(calculate(answer,scores,ID,keys,outdata);indata»ID»answer;)return0;voidcalculate(stringanswer,int&scores,stringID,stringkeys,ofstream&outdata){intlen;inti;stringkeyl;stringans;len=answer.length();scores=0;if(len<20)(outdata«ID;outdata«nToofewanswersH«endl;return;)elseif(len>20)(outdata«ID;outdata«HToomanyanswersM«endl;return;}else{for(i=0;i<20;i++){ans=answer.substr(i,1);key1=keys.substr(i,1);if(ans>Hf'llans<MaM)(outdata«ID«"InvalidanswersH«endl;return;}elseif(keyl==ans){scores+=l;}))outdata«ID«"*'«scores«endl;)第7题源代码及输入、输出信息的文本文件:fexams.txt・记事本文件⑥编辑fexams.txt・记事本文件⑥编辑⑥格式@查看(V)帮助电) abcdefabcdefabcdefab12345679876543555444644455563332221abcdefabcdefabcdefababddefbbbdefcbcdefacabcdefabcdefabcdefabcdefa^cdefabcdefabcdabcdeFghijklnnopqrstEscores.txt・记事本国旧区文件⑥编辑@格式@查看(V)?助国) 1234567209876543155554446TooFewanswer|s4445556Toomanyanswers3332221Inualidanswers附3:ProgrammingProblems第5题源代码。//sourcecodeofprogrammingproblem7.5#include<iostream>#include<fstream>#include<string>usingnamespacestd;voidphonenumber(ifstream&,string,string,char);intmain()(charflag;stringfirst,last,str3;ifstreammyfile;cout«"ifyouwantpickupphonenumberplease"«endl«"enterPH«endl;cout«"ifyoudontwanttodoit.please"«endl«"enterAM«endl;cout«"ifyoudontwanttodoit.pleaseu«endl«"enterB'*«endl;cin»flag;while(flag=='P'linag==,A,llflag=='B,){cout«"inputthefirstnameandlastH«endl;cin»first»last;phonenumber(myfile,first,last,flag);cout«nifyouwanttodoanothertime.repetitM«endl;cout«°ifnotinputNH«endl;cin»flag;)cout«nwelcometouse*'«endl;return0;}voidphonenumber(ifstream&infile,stringfirstn,stringlastn,charX){intn=0,m=0,k=0;inti=0;infile.open(Hyang.txtn);stringstrl,str2;stringstr3,str4;cout«firstn«"*'«lastn«endl;infile»strl;infile»str2;infile»str3»str4;while(infile){if(firstn==str1&&lastn==str2&&X=1P*){cout«nyourphonenumberis,,«str3«endl;n=l;m=l;k=l;}elseif(firstn==strl&&lastn==str2&&X=='A'){cout«"youraddressis*'«str4«endl;m=1;n=1;k=1;}elseif(firstn==strl&&lastn==str2&&X=='B,){cout«*'she(he)phonenumberis,'«str3«,'addressisn«str4«endl;k=l;m=l;n=l;}infile»strl;infile»str2;infile»str3»str4;infile.close();if(n==0)cout«nthereisnophoneinitH«endl;if(m==0)cout«nthereisaddressinit*'«endl;if(k==O)coulvv”can'tfindbothofthem"«endl;附4:ProgrammingProblems第2题源代码。//sourcecodeofprogrammingproblem7.2#include<iostream>#include<cmath>usingnamespacestd;voidGetroomnum(int&roomnum){cout«"Enternumberofrooms:";cin»roomnum;while(roomnum<=1){cout«HInvaliddata,enteragaincin»roomnum;}}voidGetroomsize(int&size){cout«endl«MEntersizeoftilecin»size;while(size<=0){cout«"Invaliddata,enteragain:1';cin»size;}}voidGetroomwidth(int&widfeet,int&widinch){cout«endl«"Enterroomwidth(feetandinches):";cin»widfeet»widinch;while(widfeet<=0){cout«endl«MInvaliddata,enteragain:";cin»widfeet;}while(widinch<=Ollwidinch>=12){cout«endl«"Invaliddata,enteragain:";cin»widinch;}}voidGetroomlength(int&lengthfeet,int&lengthinch){cout«endl«"Enterroomlength(feetandinches):";cin»lengthfeet»lengthinch;while(lengthfeet<=0){cout«endl«"Invaliddata,enteragain:";cin»lengthfeet;}while(lengthinch<=Olllengthinch>=l2){cout«endl«"Invaliddata,enteragain:";cin»lengthinch;}}intmain(){inttotaltile=0,roomnum,size,widfeet,widinch,lengthfeet,lengthinch;intextratile,width,length;floattilenum,boxnum;Getroomnum(roomnum);Getroomsize(size);while(roomnum)(Getroomwidth(widfeet,widinch);Getroomlength(lengthfeet,lengthinch);if((widfeet*12+widinch)%size==0)width=widfeet*12+widinch;elsewidth=(int((widfeet*12+widinch)/size)+1)*12;if((lengthfeet*12+lengthinch)%size==O)length=lengthfeet*12+lengthinch;elselength=(int((lengthfeet*12+lengthinch)/size)+1)*12;tilenum=(width*length)/(size*size);cout«endl«MRoomrequirs"«tilenum«ntiles.H«endl;totaltile=totaltile+tilenum;roomnum—;}cout«"Totaltilesrequiredis"<<totaltile«"."«endl;if(totaltile%20==0)boxnum=totaltile/20;elseboxnum=int(totaltile/20)+1;cout«"Numberofboxesneededis"<<boxnum«"."«endl;extratile=boxnum*20-totaltile;cout«"Therewillbe"«extratile«"extratile."«endl;return0;)四、注意:1.ProgrammingProblems第7题“多项选择题(单选,即正确答案唯一)”自动评分程序的实现,从性能和功能方面考虑该题目的进ー步改进。实验ハ变量的作用域和生存期ー、实验目的1,深入理解VC中变量的作用域和生存期的概念;.练习使用局部变量,全局变量;确定变量在程序中的生存期;.练习使用具有不同生存期的变量来构造函数,完成特定的程序。二、实验内容.调试本早ProgrammingExample;.编程实现并调试本章ProgrammingProblems1,3,4题(可以选2)。三、实验要求.掌握C++变量的作用域和生存期的概念;.提前写出程序源代码,设计实验测试用的输入数据,预计输出结果;四、注意:1.具有不同生存期的变量在函数中的使用。附1:ProgrammingProblems第8.1题源代码//Sourcecodeof8.1,2007.11.20#include<iostream>#include<fstream>usingnamespacestd;intmain(){inti,j,k,m=0,col=5;doublemax,min,data;doublea[10],difference[10];ifstreaminData;ofstreamoutData;inData.open(,,barometric.datH);outData.openC'differences.daf);if(!inData||!outData){cout«"Can*topenoutputfile.*';return1;while(col){for(j=0,k=0;j<6;j++,k++){inData»data;a[k]=data;}max=a[0];min=a[0];for(i=0;i<6;i++){if(a[i]>max)max=a[i];if(a[i]<min)min=a[i];jdifference[m]=max-min;outData«difference[m]«endl;//cout«difference[m]«endl;m++;col-;}max=difference[O];min=difference[O];for(i=0;i<5;i++){if(difference[i]>max)max=difference[i];if(difference[i]<min)min=difference[i];}cout«"Thegreatestdifferencefortheyear:M«max«endl;cout«"Theleastdifferencefortheyear:"«min«endl;inData.close();outData.close();return0;}附2:ProgrammingProblems第8.3题源代码以及所用的文本文件。//***** Thisprogramcalculatethecostoflumberfor an order. //*****//**♦** Lumberis pricedbyboard feet. //****♦//***** Oneboard footequalsone squarefoot,oneinch thick. //*****//***** /♦ByCao zaihui,20071116 ,Revised20100512 BY CUI*/ //*****#include<fstream>#include<iostream>#include<string>#include<iomanip>usingnamespacestd;floatcalculate(intnumber,intwidejnthighjntlength,floatprice)(floatcost;cost=number*wide*high*length*price/12;returncost;}intmain(){ stringletter,name;intnumber,intwide,high,length;floatpriceReading,price,costPerEntry,total=0;;ifstreamindata;cout«MEnteritem:H«endl:cin»letter;if(letter==,T"){cout«"Terminited!"«endl;return1;}cin»number»wide»high»length;

温馨提示

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

评论

0/150

提交评论