面向对象的C++程序设计 第六版 课后习题答案第二章

合集下载

面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)第二章2-4#includeusing namespace std;Add(int a,int b);int main(){int x,y,sum;cout>x>>y;sum = add(x,y);cout >*p;p++;}p = p-20;for( i=0;i0) countp++;if(*p>age ;try{checkagescore(name,age);}catch( string){cout<<"exception :name is exit"<<endl;continue;}catch(int){cout<<"exception :age is not proper"<<endl;continue;}cout<<"name:"<<name<<" age :"< }return 0;}第三章3-1(1)A (2)C (3)B (4)C (5)C(6)B (7)B (8)C (9)C3-7(1)main()函数中p1.age = 30;语句是错误的。

age 是类的私有成员(2)构造函数应当给常数据成员和引用成员初始化,将构造函数改为:A(int a1,int b1):a(a1),b(b1){}或A(int a1 ):a(a1),b(a){}再将main中的A a(1,2); 改为A a(1);(3)(1)在Test 类中添加语句:void print();void Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}改为void Test::Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}main函数中Init(38,15);改为:A.Init(38,15);Print();改为:A.Print();3-8(1)Constructing AConstructing BDestructing BDestructing A(2)double a,double bpoint & pp.x3-9class box{int len1,len2,len3;public:box(int l1,int l2,int l3){len1 = l1;len2 = l2; len3 = l3;} long volumn(){return len1*len2*len3;}};3-10class Test{int m1,m2;public:void Init(int a,int b){m1 = a;m2 = b;}void Pring(){cout<<m1<<" "<<m2<<endl;}};3-11略3-12}第四章4-6(1)D (2)D (3)D (4)D (5)B(6)D4-7(1)static int count = 0;这样初始化静态成员值是不对的将其改为static int count;在类外,main函数前加int Sample::count = 0;(2)#include//#includeusing namespace std;class Ctest{private:int x; const int y1;public:const int y2;Ctest(int i1,int i2):y1(i1),y2(i2) {y1 =10;//y1 为常量不能赋值x = y1;}int readme() const;};int Ctest::readme ()const{int i;i = x;x++; //常函数内不能改变成员值return x;}int main(){Ctest c(2,8);int i = c.y2;c.y2 = i;//y2为常量,不能改值i = c.y1;//y1私有,类外不能访问return 0;}将出错语句全部注释4-8(1)题中印刷错误,将class C构造函数改为: C(){cout<<"constructor C:";}运行结果为:constructor Aconstructor Bconstructor C(2)40(3)3434-9#include#includeclass Date{int year;int month;int day;public:Date(int y,int m,int d){year=y;month=m;day=d;}void disp(){cout<<year<<" "<<month<<" "<<day<<endl;}friend int count_day(Date &d,int k);friend int l(int year);friend int h(Date &d1,Date &d2);};int count_day(Date &d,int k){static int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,3 1},{31,29,31,30,31,30,31,31,30,31,30,31}};// 使用二维数组存放各月天数,第一行对应非闰年,第二行对应闰年int j,i,s;if(l(d.year))j=1;//闰年,取1else j=0;//非闰年,取0if(k)//K非0时{s=d.day;for(i=1;i<d.month;i++)//d.month为输入的月份s+=day_tab[j][i-1];}else//K为0时{s=day_tab[j][d.month]-d.day;for(i=d.month+1; i<=12; i++)s+=day_tab[j][i-1];}return s;//S为相差的天数}int l(int year){if(year%4==0&&year%100!=0||year%400==0) // 是闰年return 1;else // 不是闰年return 0;}int h(Date &d1,Date &d2){int days,day1,day2,y;if(d1.year<d2.year)//第一个日期年份小于第二个日期年份{days=count_day(d1,0);for(y=d1.year+1;y<d2.year;y++)if(l(y))//闰年。

c++_primer_plus(第六版)第二至第六章课后编程练习全部答案

c++_primer_plus(第六版)第二至第六章课后编程练习全部答案

第二章:开始学习C++//ex2.1--display your name and address#include<iostream>int main(void){using namespace std;cout<<"My name is liao chunguang and I live in hunan chenzhou.\n”;}//ex2.2--convert the furlong units to yard uints-把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using namespace std;cout<<"enter the distance measured by furlong units:";double fur;cin>>fur;cout<<"convert the furlong to yard"<<endl;double yd;yd=fur2yd(fur);cout<<fur<<" furlong is "<<yd<<" yard"<<endl;return 0;}double fur2yd(double t){return 220*t;}//ex2.3-每个函数都被调用两次#include<iostream>void mice();void see();using namespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout<<"three blind mice"<<endl;}void see(){cout<<"see how they run"<<endl;}//ex2.4#include<iostream>int main(){using namespace std;cout<<"Enter your age:";int age;cin>>age;int month;month=age*12;cout<<age<<" years is "<<month<<" months"<<endl;return 0;}//ex2.5---convert the Celsius valve to Fahrenheit value#include<iostream>double C2F(double);int main(){using namespace std;cout<<"please enter a Celsius value:";double C;cin>>C;double F;F=C2F(C);cout<<C<<" degrees Celsius is "<<F<<" degrees Fahrenheit."<<endl; return 0;}double C2F(double t){return 1.8*t+32;}//ex2.6---convert the light years valve to astronomical units--把光年转换为天文单位#include<iostream>double convert(double);//函数原型int main(){using namespace std;cout<<"Enter the number of light years:";double light_years;cin>>light_years;double astro_units;astro_units=convert(light_years);cout<<light_years<<" light_years = "<<astro_units<<" astronomical units."<<endl; return 0;}double convert(double t){return 63240*t;//1 光年=63240 天文单位}//ex2.7--显示用户输入的小时数和分钟数#include<iostream>void show();main(){using namespace std;show();return 0;}void show(){using namespace std;int h,m;cout<<"enter the number of hours:";cin>>h;cout<<"enter the number of minutes:";cin>>m;cout<<"Time:"<<h<<":"<<m<<endl;}第三章:处理数据//ex3.1—将身高用英尺(feet)和英寸(inch)表示#include<iostream>const int inch_per_feet=12;// const常量--1feet=12inches--1英尺=12英寸int main(){using namespace std;cout<<"please enter your height in inches:___\b\b\b";// \b表示为退格字符int ht_inch;cin>>ht_inch;int ht_feet=ht_inch/inch_per_feet;//取商int rm_inch=ht_inch%inch_per_feet;//取余cout<<"your height is "<<ht_feet<<" feet,and "<<rm_inch<<" inches\n";return 0;}//ex3.2--计算相应的body mass index(体重指数)#include<iostream>const int inch_per_feet=12;const double meter_per_inch=0.0254;const double pound_per_kilogram=2.2;int main(){using namespace std;cout<<"Please enter your height:"<<endl;cout<<"First,enter your height of feet part(输入你身高的英尺部分):_\b";int ht_feet;cin>>ht_feet;cout<<"Second,enter your height of inch part(输入你身高的英寸部分):_\b";int ht_inch;cin>>ht_inch;cout<<"Now,please enter your weight in pound:___\b\b\b";double wt_pound;cin>>wt_pound;int inch;inch=ht_feet*inch_per_feet+ht_inch;double ht_meter;ht_meter=inch*meter_per_inch;double wt_kilogram;wt_kilogram=wt_pound/pound_per_kilogram;cout<<endl;cout<<"Your pensonal body information as follows:"<<endl;cout<<"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram)\n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass Index(体重指数) is "<<BMI<<endl;return 0;}//ex3.3 以度,分,秒输入,以度输出#include<iostream>const int minutes_per_degree=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter a latitude in degrees,minutes,and seconds:\n";cout<<"First,enter the degrees:";int degree;cin>>degree;cout<<"Next,enter the minutes of arc:";int minute;cin>>minute;cout<<"Fianlly,enter the seconds of arc:";int second;cin>>second;double show_in_degree;show_in_degree=(double)degree+(double)minute/minutes_per_degree+(double)second/mi nutes_per_degree/seconds_per_minute;cout<<degree<<" degrees,"<<minute<<" minutes,"<<second<<"seconds ="<<show_in_degree<<" degrees\n";return 0;}//ex3.4#include<iostream>const int hours_per_day=24;const int minutes_per_hour=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter the number of seconds:";long seconds;cin>>seconds;int Day,Hour,Minute,Second;Day=seconds/seconds_per_minute/minutes_per_hour/hours_per_day;Hour=seconds/seconds_per_minute/minutes_per_hour%hours_per_day;Minute=seconds/seconds_per_minute%minutes_per_hour;Second=seconds%seconds_per_minute;cout<<seconds<<"seconds = "<<Day<<" days,"<<Hour<<" hours,"<<Minute<<" minutes,"<<Second<<" seconds\n";return 0;}//ex3.5#include<iostream>int main(){using namespace std;cout<<"Enter the world population:";long long world_population;cin>>world_population;cout<<"Enter the population of the US:";long long US_population;cin>>US_population;double percentage;percentage=(double)US_population/world_population*100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n";return 0;}//ex3.6 汽车耗油量-美国(mpg)or欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the miles of distance you have driven:";double m_distance;cin>>m_distance;cout<<"Enter the gallons of gasoline you have used:";double m_gasoline;cin>>m_gasoline;cout<<"Your car can run "<<m_distance/m_gasoline<<" miles per gallon\n";cout<<"Computing by European style:\n";cout<<"Enter the distance in kilometers:";double k_distance;cin>>k_distance;cout<<"Enter the petrol in liters:";double k_gasoline;cin>>k_gasoline;cout<<"In European style:"<<"your can used "<<100*k_gasoline/k_distance<<" liters of petrol per 100 kilometers\n";return 0;}//ex3.7 automobile gasoline consumption-耗油量--欧洲风格(L/100Km)转换成美国风格(mpg) #include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"European style(liters per 100 kilometers):";double Euro_style;cin>>Euro_style;cout<<"Converts to U.S. style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<62.14*3.875/Euro_style<<" mpg\n";return 0;}// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Converts to U.S. style(miles per gallon):12.4 L/100Km = 19.4187 mpgPress any key to continue// ex3.7 automobile gasoline consumption-耗油量--美国风格(mpg)转换成欧洲风格(L/100Km) #include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n";return 0;}// Enter the automobile gasoline consumption figure inU.S. style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 12.6733L/100KmPress any key to continue第四章复合类型//ex4.1 display the information of student#include<iostream>const int Asize=20;using namespace std;struct student//定义结构描述{char firstname[Asize];char lastname[Asize];char grade;int age;};void display(student);//函数原型放在结构描述后int main(){cout<<"what is your first name?"<<endl;student lcg;//创建结构变量(结构数据对象)cin.getline(lcg.firstname,Asize);cout<<"what is your last name?"<<endl;cin.getline(stname,Asize);cout<<"what letter grade do you deserve?"<<endl;cin>>lcg.grade;cout<<"what is your age?"<<endl;cin>>lcg.age;display(lcg);return 0;}void display(student name){cout<<"Name: "<<name.firstname<<","<<stname<<endl;cout<<"Grade:"<<char(name.grade+1)<<endl;cout<<"Age:"<<name.age<<endl;}//ex4.2 use the string-class instead of char-array#include<iostream>#include<string>int main(){using namespace std;string name,dessert;cout<<"Enter your name: \n";getline(cin,name);cout<<"Enter your favorite dessert: \n";getline(cin,dessert);cout<<"I have some delicious "<<dessert;cout<<" for you, "<<name<<".\n";return 0;}//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I.rdbuf()->sbumpc();//修改后的break; }ex4.3 输入其名和姓,并组合显示#include<iostream>#include<cstring>const int Asize=20;int main(){using namespace std;char fname[Asize];char lname[Asize];char fullname[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin.getline(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在lname[]数组中cin.getline(lname,Asize);strncpy(fullname,lname,Asize);//把姓lname复制到fullname空数组中strcat(fullname,", ");//把“,”附加到上述fullname尾部strncat(fullname,fname,Asize);//把fname名字附加到上述fullname尾部fullname[2*Asize]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;}//ex4.4 使用string对象存储、显示组合结果#include<iostream>#include<string>int main(){using namespace std;string fname,lname,attach,fullname;cout<<"Enter your first name:";getline(cin,fname);//note:将一行输入读取到string类对象中使用的是getline(cin,str)//它没有使用句点表示法,所以不是类方法cout<<"Enter your last name:";getline(cin,lname);attach=", ";fullname=lname+attach+fname;cout<<"Here's the information in a single string:"<<fullname<<endl;return 0;}//ex4.5 declare a struct and initialize it 声明结果并创建一个变量#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack={"Mocha Munch",2.3,350};cout<<"Here's the information of snack:\n";cout<<"brand:"<<snack.brand<<endl;cout<<"weight:"<<snack.weight<<endl;cout<<"calory:"<<snack.calory<<endl;return 0;}//ex4.6 结构数组的声明及初始化#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack[3]={{"Mocha Munch",2.3,350},{"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)//利用for循环来显示snack变量的内容{cout<<snack[i].brand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}//ex4.7 pizza披萨饼#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza pie;//创建一个名为pie的结构变量cout<<"What's the name of pizza company:";cin.getline(pany,Size);cout<<"What's the diameter of pizza:";cin>>pie.diameter;cout<<"What's the weight of pizza:";cin>>pie.weight;cout<<"company:"<<pany<<endl;cout<<"diameter:"<<pie.diameter<<"inches"<<endl;cout<<"weight:"<<pie.weight<<"ounches"<<endl;return 0;}//ex4.8 pizza pie 披萨饼使用new创建动态结构#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza *pie=new pizza;//使用new创建动态结构cout<<"What's the diameter of pizza:";cin>>pie->diameter;cin.get();//读取下一个字符cout<<"What's the name of pizza company:";cin.get(pie->company,Size);cout<<"What's the weight of pizza:";cin>>pie->weight;cout<<"diameter:"<<pie->diameter<<" inches"<<endl;cout<<"company:"<<pie->company<<endl;cout<<"weight:"<<pie->weight<<" ounches"<<endl;delete pie;//delete释放内存return 0;}//ex.4.9 使用new动态分配数组—方法1#include<iostream>#include<string>using namespace std;struct CandyBar{string brand;double weight;int calory;};int main(){CandyBar *snack= new CandyBar[3];snack[0].brand="A";//单个初始化由new动态分配的内存snack[0].weight=1.1;snack[0].calory=200;snack[1].brand="B";snack[1].weight=2.2;snack[1].calory=400;snack[2].brand="C";snack[2].weight=4.4;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " << snack[i].brand << endl;cout << " weight: " << snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}//ex.4.10 数组—方法1#include <iostream>int main(){using namespace std;const int Size = 3;int success[Size];cout<<"Enter your success of the three times 40 meters running:\n";cin >> success[0]>>success[1]>>success[2];cout<<"success1:"<<success[0]<<endl;cout<<"success2:"<<success[1]<<endl;cout<<"success3:"<<success[2]<<endl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<endl;return 0;}//ex.4.10 array—方法2#include <iostream>#include <array>int main(){using namespace std;array<double,4>ad={0};cout<<"Enter your success of the three times 40 meters running:\n";cin >> ad[0]>>ad[1]>>ad[2];cout<<"success1:"<<ad[0]<<endl;cout<<"success2:"<<ad[1]<<endl;cout<<"success3:"<<ad[2]<<endl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<endl;return 0;}第五章循环和关系表达式//ex.5.1#include <iostream>int main(){using namespace std;cout<<"Please enter two integers: ";int num1,num2;cin>>num1>>num2;int sum=0;for(int temp=num1;temp<=num2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<num1<<" to "<<num2<<" is "<<sum<<endl; return 0;}//ex.5.2#include <iostream>#include<array>int main(){using namespace std;array<long double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)cout<<i<<"! = "<<ad[i]<<endl;return 0;}//ex.5.3#include <iostream>int main(){using namespace std;cout<<"Please enter an integer: ";int sum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"So far, the sum is "<<sum<<endl;cout<<"Please enter an integer: ";}return 0;}//ex.5.4#include <iostream>int main(){using namespace std;double sum1,sum2;sum1=sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo的投资价值才能超过Daphne的投资价值。

面向对象程序设计C课后题答案

面向对象程序设计C课后题答案

第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。

这种范型的主要特征是:程序=对象+消息。

面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。

第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。

面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。

这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。

[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。

对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。

类和对象之间的关系是抽象和具体的关系。

类是多个对象进行综合抽象的结果,一个对象是类的一个实例。

在面向对象程序设计中,总是先声明类,再由类生成对象。

类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。

[1_3]现实世界中的对象有哪些特征?请举例说明。

对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。

(2)需要用属性来描述它的某些特性。

(3)有一组操作,每一个操作决定了对象的一种行为。

(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。

例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。

[VIP专享]面向对象程序设计第二章课后答案

[VIP专享]面向对象程序设计第二章课后答案

1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。

命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。

在作用域范围内使用命名空间就可以访问命名空间定义的标识符。

有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。

(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。

C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。

内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。

在编译时,C++将用内联函数程序代码替换对它每次的调用。

这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。

但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。

因此,内联函数是一种空间换时间的方案。

函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。

3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。

编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。

使得重载的函数虽然函数名相同,但功能却不完全相同。

在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。

Visual C++程序设计案例教程第二章课后答案

Visual C++程序设计案例教程第二章课后答案
D. CTest()和int~CTest()
(4)已知CTest类定义如下,t是CTest类的对象,则正确的成员访问是。(A)
class CTest {
public:
void SetA(int x)
{ a=x; }
private:
int a;
};
A. t.SetA(10)
B. t.a
C. t-> SetA(10)
(5)继承是通过基类与派生类来实现的。基类的成员在派生类中的访问权限由___继承方式___决定。
(6)派生类的对象可以当成____基类____的对象来处理,因此,指向_____基类______对象的指针也可以指向派生类的对象。
(7)对基类对象成员的初始化是通过___构造函数_____语法实现的。
(8)如果一个类中含有纯虚函数,则称该类为________抽象类______。
};
<各个成员函数的实现>
对象的定义格式:类名对象名;
(2)分析构造函数和析构函数的作用。
构造函数:用于创建和初始化实例;析构函数:析构函数用于销毁类的实例。
(3)简述基类和派生类关系。
任何一个类都可以派生出一个新类,派生类也可以再派生出新类,因此,基类和派生类是相对而言的。 基类与派生类之间的关系有:a:派生类是基类的具体化b:派生类是基类定义的延续c:派生类是基类的组合
};
class Point:public CShape
{
public:
Point(float a,float b);
virtual float area();
virtual float volume();
virtual void show();

面向对象程序设计第二章课后答案说课讲解

面向对象程序设计第二章课后答案说课讲解

面向对象程序设计第二章课后答案1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。

命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。

在作用域范围内使用命名空间就可以访问命名空间定义的标识符。

有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。

(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。

C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。

内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。

在编译时,C++将用内联函数程序代码替换对它每次的调用。

这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。

但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。

因此,内联函数是一种空间换时间的方案。

函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。

3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。

编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。

使得重载的函数虽然函数名相同,但功能却不完全相同。

在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。

面向对象课后题答案

面向对象课后题答案
C. 使用内联函数,可以加快程序执行的速度,但会增加程序代码的大小
D. 使用内联函数,可以减小程序代码大小,但使程序执行的速度减慢
【结果分析】
内联函数主要是解决程序的运行效率问题。在程序编译时,编译系统将程序中出现内联函数调用的地方用函数体进行替换,进而减少了程序运行的时间,但会增加程序代码的大小。它是以空间换取时间,因此内联函数适用于功能不太复杂,但要求被频繁调用的函数。
B. 对象实际是功能相对独立的一段程序
C. 各个对象间的数据可以共享是对象的一大优点
D. 在面向对象的程序中,对象之间只能通过消息相互通信
【结果分析】
对象是计算机内存中的一块区域。在对象中,不但存有数据,而且存有代码,使得每个对象在功能上相互之间保持相对独立。对象之间存在各种联系,但它们之间只能通过消息进行通信。
C. C++对C语言进行了一些改进 D. C++和C语言都是面向对象的
【结果分析】
C语言是面向过程的。C++语言是一种经过改进的更为优化的C语言,是一种混合型语言,既面向过程也面向对象。
(6) 面向对象的程序设计将数据结构与( A )放在一起,作为一个相互依存、不可分割的整体来处理。
A. 算法 B. 信息 C. 数据隐藏 D. 数据抽象
四、 判断题
(1) 在高级程序设计语言中,一般用类来实现对象,类是具有相同属性和行为的一组对象的集合,它是创建对象的模板。( √ )
(2) C++语言只支持面向对象技术的抽象性、封装性、继承性等特性,而不支持多态性。( × )
【结果分析】
C++语言不仅支持面向对象技术的抽象性、封装性、继承性等特性,而且支持多态性。

谭浩强《C++面向对象程序设计》第二章答案

谭浩强《C++面向对象程序设计》第二章答案

谭浩强《C++面向对象程序设计》第二章答案-CAL-FENGHAI-(2020YEAR-YICAI)_JINGBIAN第二章1#include <iostream>using namespace std;class Time{public:void set_time();void show_time();private: //成员改为公用的 int hour;int minute;int sec;};void Time::set_time() //在main函数之前定义{cin>>hour;cin>>minute;cin>>sec;}void Time::show_time() //在main 函数之前定义{cout<<hour<<":"<<minute<<":"<<sec<< endl;}int main(){Time t1;();();return 0;}2:#include <iostream>using namespace std;class Time{public:void set_time(void){cin>>hour;cin>>minute;cin>>sec;}void show_time(void){cout<<hour<<":"<<minute<<":"<<sec<< endl;}private: int hour;int minute;int sec;};Time t;int main(){();();return 0;}3:#include <iostream>using namespace std;class Time{public:void set_time(void);void show_time(void);private:int hour;int minute;int sec;};void Time::set_time(void){cin>>hour;cin>>minute;cin>>sec;}void Time::show_time(void){cout<<hour<<":"<<minute<<":"<<sec<< endl;}Time t;int main(){ ();();return 0;}4://#include <iostream>using namespace std;#include ""int main(){Student stud;();();return 0;}//(即#include "" //在此文件中进行函数的定义#include <iostream>using namespace std; //不要漏写此行void Student::display( ){ cout<<"num:"<<num<<endl;cout<<"name:"<<name<<endl;cout<<"sex:"<<sex<<endl;}void Student::set_value(){ cin>>num;cin>>name;cin>>sex;}5://#include <iostream>#include ""int main(){Array_max arrmax;();();();return 0;}//#include <iostream>using namespace std;#include ""void Array_max::set_value() { int i;for (i=0;i<10;i++)cin>>array[i];}void Array_max::max_value() {int i;max=array[0];for (i=1;i<10;i++)if(array[i]>max) max=array[i]; }void Array_max::show_value() {cout<<"max="<<max<<endl; }6:解法一#include <iostream>using namespace std;class Box{public:void get_value();float volume();void display();public:float lengh;float width; float height;};void Box::get_value(){ cout<<"please input lengh, width,height:";cin>>lengh;cin>>width;cin>>height;}float Box::volume(){ return(lengh*width*height);}void Box::display(){ cout<<volume()<<endl;}int main(){Box box1,box2,box3;();cout<<"volmue of bax1 is "; ();();cout<<"volmue of bax2 is "; ();();cout<<"volmue of bax3 is "; ();return 0;}解法二:#include <iostream>using namespace std;class Box{public:void get_value();void volume();void display();public:float lengh;float width;float height;float vol;};void Box::get_value(){ cout<<"please input lengh, width,height:";cin>>lengh;cin>>width;cin>>height;}void Box::volume(){ vol=lengh*width*height;}void Box::display(){ cout<<vol<<endl;}int main(){Box box1,box2,box3;();();cout<<"volmue of bax1 is "; ();();();cout<<"volmue of bax2 is "; ();();();cout<<"volmue of bax3 is "; ();return 0;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Chapter 2C++ Basics1. Solutions to the Programming Projects:1. Metric - English units ConversionA metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a box of cereal in ounces then output this weight in metric tons, along with the number of boxes to yield a metric ton of cereal.Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' to tell us whether to divide or multiply:1 metric tons14 ounces * * = 0.000397 metric tons35,273 ouncesThe use of units will simplify the determination of whether to divide or to multiply in making a conversion. Notice that ounces/ounce becomes unit-less, so that we are left with metric ton units. The number of ounces will be very, very much larger than the number of metric tons. It is then reasonable to divide the number of ounces by the number of ounces in a metric ton to get the number of metric tons.Now let metricTonsPerBox be the weight of the cereal box in metric tons. Let ouncesPerBox the be the weight of the cereal box in ounces. Then in C++ the formula becomes:const double ouncesPerMetric_ton = 35272.92; metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon;This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal:boxesPerMetricTon = 1 / metricTonsPerBox;Once this analysis is made, the code proceeds quickly://Purpose: To convert cereal box weight from ounces to // metric tons to compute number of boxes to make up a // metric ton of cereal.#include <iostream>using namespace std;const double ouncesPerMetricTon = 35272.92;int main(){double ouncesPerBox, metricTonsPerbox,boxesPerMetricTon;char ans = 'y';while( 'y' == ans || 'Y' == ans ){cout << “enter the weight in ounces of your”<< “favorite cereal:” <<end l;cin >> ouncesPerBox;metricTonsPerbox =ouncesPerBox / ouncesPerMetricTon;boxesPerMetricTon = 1 / metricTonsPerbox;cout << "metric tons per box = "<< metricTonsPerbox << endl;cout << "boxes to yield a metric ton = "<< boxesPerMetricTon << endl;cout << " Y or y continues, any other character ”<< “terminates." << endl;cin >> ans;}return 0;}A sample run follows:enter the weight in ounces of your favorite cereal:14metric tons per box = 0.000396905boxes to yield a metric ton = 2519.49Y or y continues, any other characters terminates.yenter the weight in ounces of your favorite cereal:20metric tons per box = 0.000567007boxes to yield a metric ton = 1763.65Y or y continues, any other characters terminates.n2. Lethal DoseCertain artificial sweeteners are poisonous at some dosage level. It is desired to know how much soda a dieter can drink without dying. The problem statement gives no information about how to scale the amount of toxicity from the dimensions of the experimental mouse to the dimensions of the dieter. Hence the student must supply this necessary assumption as basis for the calculation.This solution supposes the lethal dose is directly proportional to the weight of the subject, henceweightOfDieterlethalDoseDieter = lethalDoseMouse *weightOfMouseThis program accepts weight of a lethal dose for a mouse, the weight of the mouse, and the weight of the dieter, and calculates the amount of sweetener that will just kill the dieter, based on the lethal dose for a mouse in the lab. If the student has problems with grams and pounds, a pound is 454 grams.It is interesting that the result probably wanted is a safe number of cans, while all the data can provide is the minimum lethal number! Some students will probably realize this, but my experience is that most will not. I just weighed a can of diet pop and subtracted the weight of an empty can. The result is about 350 grams. The label claims 355 ml, which weighs very nearly 355 grams. To get the lethal number of cans from the number of grams of sweetener, you need the number of grams ofsweetener in a can of pop, and the concentration of sweetener, which the problem assumes 0.1% , that is a conversion factor of 0.001.gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/cancans = lethalDoseDieter / (0.35 grams / can)////Input: lethal dose of sweetener for a lab mouse, weights// of mouse and dieter, and concentration of sweetener in a // soda.//Output: lethal dose of soda in number of cans.//Assumption: lethal dose proportional to weight of subject// Concentration of sweetener in the soda is 1/10 percent #include <iostream>using namespace std;const double concentration = .001; // 1/10 of 1 percentconst double canWeight = 350;const double gramsSweetnerPerCan = canWeight concentration; //units of grams/canint main(){double lethalDoseMouse, lethalDoseDieter,weightMouse, weightDieter; //units: gramsdouble cans;char ans;do{cout << "Enter the weight of the mouse in grams"<< endl;cin >> weightMouse;cout << "Enter the lethal dose for the mouse in“<< ”grams " << endl;cin >> lethalDoseMouse;cout << "Enter the desired weight of the dieter in”<<“ grams " << endl;cin >> weightDieter;lethalDoseDieter =lethalDoseMouse weightDieter/weightMouse;cout << "For these parameters:\nmouse weight: "<< weightMouse<< " grams " << endl<< "lethal dose for the mouse: "<< lethalDoseMouse<< "grams" << endl<< "Dieter weight: " << weightDieter<< " grams " << endl<< "The lethal dose in grams of sweetener is: "<< lethalDoseDieter << endl;cans = lethalDoseDieter / gramsSweetnerPerCan;cout << "Lethal number of cans of pop: "<< cans << endl;cout << "Y or y continues, any other character quits"<< endl;cin >> ans;} while ( 'y' == ans || 'Y' == ans );return 0;}A typical run follows:17:23:09:~/AW$ a.outEnter the weight of the mouse in grams15Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 15 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 302667 Lethal number of cans of pop: 864762Y or y continues, any other character quitsyEnter the weight of the mouse in grams30Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 30 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 151333 Lethal number of cans of pop: 432381Y or y continues, any other character quitsq17:23:56:~/AW$3. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. This program is to accept the previous annual salary, then outputs the retroactive pay due the employee, the new annual salary, and the new monthly salary. Allow user to repeat as desired. The appropriate formulae are:const double INCREASE = 0.076;newSalary = salary * (1 + INCREASE);monthly = salary / 12;retroactive = (salary – oldSalary)/2;The code follows:////Given 6 mos retroactive 7.6% pay increase,//input salary//Output new annual and monthly salaries, retroactive pay#include <iostream>using namespace std;const double INCREASE = 0.076;int main(){double oldSalary, salary, monthly, retroactive;char ans;cout << "Enter current annual salary." << endl<< "I'll return new annual salary, monthly ”<< “salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarysalary = oldSalary*(1+INCREASE);//new annual salarymonthly = salary/12;retroactive = (salary – oldSalary)/2;cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}17:50:12:~/AW$ a.outEnter current annual salary.100000I'll return new annual salary, monthly salary, andretroactive pay.new annual salary 107600new monthly salary 8966.67retroactive salary due: 38004. Retroactive Salary// File: Ch2.4.cpp// Modify program from Problem #3 so that it calculatesretroactive// salary for a worker for a number of months entered by the user. //Given a 7.6% pay increase,//input salary//input number of months to compute retroactive salary//Output new annual and monthly salaries, retroactive pay#include <iostream>const double INCREASE = 0.076;int main(){using std::cout;using std::cin;using std::endl;double oldSalary, salary, monthly, oldMonthly, retroactive;int numberOfMonths; // number of months to pay retroactiveincreasechar ans;cout << "Enter current annual salary and a number of months\n"<< "for which you wish to compute retroactive pay.\n"<< "I'll return new annual salary, monthly "<< "salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarycin >> numberOfMonths;salary = oldSalary * (1+INCREASE); //new annual salaryoldMonthly = oldSalary/12;monthly = salary/12;retroactive = (monthly - oldMonthly) * numberOfMonths;// retroactive = (salary - oldSalary)/2; // six monthsretroactive pay increase.cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}/*Typical runEnter current annual salary and a number of monthsfor which you wish to compute retroactive pay.I'll return new annual salary, monthly salary, and retroactive pay. 120009new annual salary 12912new monthly salary 1076retroactive salary due: 684Press any key to continue*/5. No solution provided.6. No solution provided.7. PayrollThis problem involves payroll and uses the selection construct. A possible restatement: An hourly employee's regular payRate is $16.78/hour for hoursWorked <= 40 hours. If hoursWorked > 40 hours, then (hoursWorked -40) is paid at an overtime premium rate of 1.5 * payRate. FICA (social security) tax is 6% and Federal income tax is 14%. Union dues of$10/week are withheld. If there are 3 or more covered dependents, $15 more is withheld for dependent health insurance.a) Write a program that, on a weekly basis, accepts hours worked then outputs gross pay, each withholding amount, and net (take-home) pay.b) Add 'repeat at user discretion' feature.I was unpleasantly surprised to find that with early GNU g++ , you cannot use a leading 0 (such as an SSN 034 56 7891) in a sequence of integer inputs. The gnu iostreams library took the integer to be zero and went directly to the next input! You either have to either use an array of char, or 9 char variables to avoid this restriction.Otherwise, the code is fairly straight forward.//file //pay roll problem://Inputs: hoursWorked, number of dependents//Outputs: gross pay, each deduction, net pay////This is the 'repeat at user discretion' version//Outline://In a real payroll program, each of these values would be//stored in a file after the payroll calculation was printed //to a report.////regular payRate = $10.78/hour for hoursWorked <= 40//hours.//If hoursWorked > 40 hours,// overtimePay = (hoursWorked - 40) * 1.5 * PAY_RATE.//FICA (social security) tax rate is 6%//Federal income tax rate is 14%.//Union dues = $10/week .//If number of dependents >= 3// $15 more is withheld for dependent health insurance.//#include <iostream>using namespace std;const double PAY_RATE = 16.78;const double SS_TAX_RATE = 0.06;const double FedIRS_RATE = 0.14;const double STATE_TAX_RATE = 0.05;const double UNION_DUES = 10.0;const double OVERTIME_FACTOR = 1.5;const double HEALTH_INSURANCE = 15.0;int main(){double hoursWorked, grossPay, overTime, fica,incomeTax, stateTax, union_dues, netPay;int numberDependents, employeeNumber;char ans;//set the output to two places, and force .00 for cents cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);// compute payrolldo{cout << "Enter emplo yee SSN (digits only,”<< “ no spaces or dashes) \n”;cin >> employeeNumber ;cout << “Please the enter hours worked and number “<< “of employees.” << endl;cin >> hoursWorked ;cin >> numberDependents;cout << endl;if (hoursWorked <= 40 )grossPay = hoursWorked * PAY_RATE;else{overTime =(hoursWorked - 40) * PAY_RATE * OVERTIME_FACTOR; grossPay = 40 * PAY_RATE + overTime;}fica = grossPay * SS_TAX_RATE;incomeTax = grossPay * FedIRS_RATE;stateTax = grossPay * STATE_TAX_RATE;netPay =grossPay - fica - incomeTax- UNION_DUES - stateTax;if ( numberDependents >= 3 )netPay = netPay - HEALTH_INSURANCE;//now print report for this employee:cout << "Employee number: "<< employeeNumber << endl;cout << "hours worked: " << hoursWorked << endl; cout << "regular pay rate: " << PAY_RATE << endl;if (hoursWorked > 40 ){cout << "overtime hours worked: "<< hoursWorked - 40 << endl;cout << "with overtime premium: "<< OVERTIME_FACTOR << endl;}cout << "gross pay: " << grossPay << endl;cout << "FICA tax withheld: " << fica << endl;cout << "Federal Income Tax withheld: "<< incomeTax << endl;cout << "State Tax withheld: " << stateTax << endl;if (numberDependents >= 3 )cout << "Health Insurance Premium withheld: "<< HEALTH_INSURANCE << endl;cout << "Flabbergaster's Union Dues withheld: "<< UNION_DUES << endl;cout << "Net Pay: " << netPay << endl << endl;cout << "Compute pay for another employee?”<< “ Y/y repeats, any other ends" << endl;cin >> ans;} while( 'y' == ans || 'Y' == ans );return 0;}//A typical run:14:26:48:~/AW $ a.outEnter employee SSN (digits only, no spaces or dashes) 234567890Please the enter hours worked and number of employees.101Employee number: 234567890hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Flabbergaster's Union Dues withheld: 10.00Net Pay: 115.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 987654321Please the enter hours worked and number of employees.103Employee number: 987654321hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 80.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 123456789Please the enter hours worked and number of employees.453Employee number: 123456789hours worked: 45.00regular pay rate: 16.78overtime hours worked: 5.00with overtime premium: 1.50gross pay: 797.05FICA tax withheld: 47.82Federal Income Tax withheld: 111.59State Tax withheld: 39.85Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 552.79Compute pay for another employee? Y/y repeats, any other ends n14:28:12:~/AW $8. No solution provided.9. Installment Loan TimeNo down payment, 18 percent / year, payment of $50/month, payment goes first to interest, balance to principal. Write a program that determines the number of months it will take to pay off a $1000 stereo. The following code also outputs the monthly status of the loan.#include <iostream>using namespace std;// chapter 2 problem 9.int main(){double principal = 1000.;double interest, rate = 0.015;int months = 0;cout << "months\tinterest\tprincipal" << endl;while ( principal > 0 ){months++;interest = principal * rate;principal = principal - (50 - interest);if ( principal > 0 )cout << months << "\t" << interest << "\t\t"<< principal << endl;}cout << "number of payments = " << months;//undo the interation that drove principal negative: principal = principal + (50 - interest);//include interest for last month:interest = principal * 0.015;principal = principal + interest;cout << " last months interest = " << interest;cout << " last payment = " << principal << endl;return 0;}Testing is omitted for this problem.10. No solution provided.11. Separate numbers by sign, compute sums and averages// Programming Problem 11// Read ten int values output// sum and average of positive numbers// sum and average of nonpositive numbers,// sum and average of all numbers,//// Averages are usually floating point numbers.We mulitply// the numerator of the average computation by 1.0 to make// the int values convert automatically to double.#include <iostream>int main(){using std::cout;using std::cin;using std::endl;int value, sum = 0, sumPos = 0, sumNonPos = 0;int countPos = 0, countNeg = 0;cout << "Enter ten numbers, I'll echo your number and compute\n"<< "the sum and average of positive numbers\n"<< "the sum and average of nonpositive numbers\n"<< "the sum and average of all numbers\n\n";for(int i =0; i < 10; i++){cin >> value;cout << "value " << value <<endl;sum += value;if (value > 0){sumPos += value;countPos++;}else{sumNonPos += value;countNeg++;}}cout << "Sum of Positive numbers is "<< sumPos << endl;cout << "Average of Positive numbers is "<< (1.0 * sumPos) / countPos << endl;cout << "Sum of NonPositive numbers is "<< sumNonPos << endl;cout << "Average of NonPositive numbers is "<< (1.0 * sumNonPos) / countNeg << endl;cout << "Sum " << sum << endl;cout << "Average is " << (1.0 * sum)/(countPos + countNeg) << endl;if((countPos + countNeg)!= 10)cout << "Count not 10, error some place\n";return 0;}/*Typical runEnter ten numbers, I'll echo your number and computethe sum and average of positive numbersthe sum and average of nonpositive numbersthe sum and average of all numbers4value 45value 5-1value -13value 3-4value -4-3value -39value 98value 87value 72value 2Sum of Positive numbers is 38Average of Positive numbers is 5.42857Sum of NonPositive numbers is -8Average of NonPositive numbers is -2.66667Sum 30Average is 3Press any key to continue*/12.//***********************************************************************// Ch2Proj12.cpp//// This program computes the square root of a number n// using the Babylonian algorithm.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double guess, previousguess, n, r;// Input number to compute the square root ofcout << "Enter number to compute the square root of." << endl;cin >> n;// Initial guesspreviousguess = n;guess = n /2;// Repeat until guess is within 1% of the previous guesswhile (((previousguess - guess) / previousguess) > 0.01){previousguess = guess;r = n / guess;guess = (guess + r) / 2;}cout << "The estimate of the square root of " << n << " is "<< guess << endl;return 0;}13.//*********************************************************************** // Ch2Proj13.cpp//// This program inputs a speed in MPH and converts it to// Minutes and Seconds per mile, as might be output on a treadmill.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double milesPerHour, hoursPerMile, minutesPerMile, secondsPace;int minutesPace;// Input miles per hourcout << "Enter speed in miles per hour:" << endl;cin >> milesPerHour;// Compute inverse, which is hours per milehoursPerMile = 1.0 / milesPerHour;// Convert to minutes per mile which is 60 seconds/hour * hoursPerMile minutesPerMile = 60 * hoursPerMile;// Extract minutes by converting to an integer, while// truncates any value after the decimal pointminutesPace = static_cast<int>(minutesPerMile);// Seconds is the remaining number of minutes * 60secondsPace = (minutesPerMile - minutesPace) * 60;cout << milesPerHour << " miles per hour is a pace of " << minutesPace << " minutes and " << secondsPace << " seconds. " << endl;return 0;}14.//*********************************************************************** // Ch2Proj14.cpp//// This program plays a simple game of "Mad Libs".//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){string instructorName;string yourName;string food;int num;string adjective;string color;string animal;cout << "Welcome to Mad Libs! Enter your name: " << endl;cin >> yourName;cout << "Enter your instructor's first or last name." << endl;cin >> instructorName;cout << "Enter a food." << endl;cin >> food;cout << "Enter a number between 100 and 120." << endl;cin >> num;cout << "Enter an adjective." << endl;cin >> adjective;cout << "Enter a color." << endl;cin >> color;cout << "Enter an animal." << endl;cin >> animal;cout << endl;cout << "Dear Instructor " << instructorName << "," << endl;cout << endl;cout << "I am sorry that I am unable to turn in my homework at this time."<< endl;cout << "First, I ate a rotten " << food << " which made me turn " << color << " and " << endl;cout << "extremely ill. I came down with a fever of " << num << "." << endl;cout << "Next, my " << adjective << " pet " << animal << " must have " <<"smelled the remains " << endl;cout << "of the " << food << " on my homework, because he ate it. I am " <<"currently " << endl;cout << "rewriting my homework and hope you will accept it late." << endl;cout << endl;cout << "Sincerely," << endl;cout << yourName << endl;return 0;}2. Outline of topics in the chapter2.1 Variables and assignments2.2 Input and Output2.3 Data Types and Expressions2.4 Simple Flow of Controlbranchinglooping2.5 Program Style3. General Remarks on the chapter:This chapter is a very brief introduction to the minimum C++ necessary to write simple programs.Comments in the Student's code:Self documenting code is a code feature to be striven for. The use of identifier names that have meaning within the context of the problems being solved goes a long way in this direction.Code that is not self documenting for whatever reasons may be made clearer by appropriate (minimal) comments inserted in the code."The most difficult feature of any programming language to master is thecomment."-- a disgruntled maintenance programmer."Where the comment and the code disagree, both should be assumed to be inerror."-- an experienced maintenance programmer.With these cautions in mind, the student should place remarks at the top of file containing program components, describing the purpose. Exactly what output is required should be specified, and any conditions on the input to guarantee correct execution should also bespecified.Remarks can clarify difficult points, but remember, if the comment doesn't add to what can be gleaned from the program code itself, the comment is unnecessary, indeed it gets in the way. Good identifier names can reduce the necessity for comments!iostreams vs stdioYou will have the occasional student who has significant C programming experience. These students will insist on using the older stdio library input-output (for example, printf). Discourage this, insist on C++ iostream i/o. The reason is that the iostream library understands and uses the type system of C++. You have to tell stdio functions every type for every output attempted. And if you don't get it right, then the error may not be obvious in the output. Either iostreams knows the type, or the linker will complain that it doesn't have the member functions to handle the type you are using. Then it is easy enough to write stream i/o routines to do the i/o in a manner consistent with the rest of the library.。

相关文档
最新文档