C++程序设计练习题及答案第五章类与对象

合集下载

《C++面向对象程序设计答案》-第五章--谭浩强-清华大学出版社

《C++面向对象程序设计答案》-第五章--谭浩强-清华大学出版社

1:#include<iostream>usingnamespacestd;classStudent{public:voidget_value(){cin>>num>>name>>sex;}voiddisplay(){cout<<"num:"<<num<<endl;cout<<"name:"<<name<<endl;cout<<"sex:"<<sex<<endl;}private:intnum;charname[10];charsex;};classStudent1:publicStudent{public:voidget_value_1(){get_value();cin>>age>>addr;}voiddisplay_1(){cout<<"age:"<<age<<endl;//引用派生类的私有成员,正确。

cout<<"address:"<<addr<<endl;}//引用派生类的私有成员,正确。

private:intage;charaddr[30];};intmain(){Student1stud1;stud1.get_value_1();stud1.display();stud1.display_1();return0;}2:#include<iostream>usingnamespacestd;classStudent{public:voidget_value(){cin>>num>>name>>sex;}voiddisplay(){cout<<"num:"<<num<<endl;cout<<"name:"<<name<<endl;cout<<"sex:"<<sex<<endl;}private:intnum;charname[10];charsex;};classStudent1:privateStudent{public:voidget_value_1(){get_value();cin>>age>>addr;}voiddisplay_1(){display();cout<<"age:"<<age<<endl;//引用派生类的私有成员,正确。

程序设计基础课后答案 第五章

程序设计基础课后答案 第五章
{
int i,m,n;
m=strlen(dest);
n=strlen(a)-m;
try//用于抛出错误
{
for(i=0;i<=n;i++)
{
int k=i;/r(int j=0;j<=m-1;j++)
{
if(a[k]==dest[j])
cout<<"values after function"<<big<<"and"<<small<<endl;
}
分析:输出结果:Values before function 2002 and 0
Values after function 2002 and 0
在函数调用中,可以通过值传递方式在函数间传递数据。但是,这种传递无法改变实参的值。只是因为在进入被调用函数时,变量进行了复制。被调用函数的任何更改和实参没有任何联系。所以,在主程序中打印它的局部变量时,变量值没有任何改变。
double add(double,double);
void main()
{
cout<<add(5,10)<<endl;
cout<<add(5.0,10.6)<<endl;
}
int add(int x,int y)
{
return x+y;
}
double add(double a, double b)
四、编程题
2、编写一个函数,在一个字符串数组中查找"Hello",如果找回返回指向“Hello”开始出的指针;否则抛出一个异常“Not Found”.

《类与对象》课后习题(含答案)

《类与对象》课后习题(含答案)

问题一:程序执行结果是
问题二:本程序中,y、z 是 class Test{ public: static int Data; }; int Test::Data=100; //A void main(void) { Test t1,t2; t1.Data=200; t2.Data=300; //B //C
2、写出程序的输出结果。 #include <iostream> #include <cstring> using namespace std; class SomeClass { int One , Two; public: SomeClass(int a = 1, int b = 1) { One = a; Two = b; cout << "Structor" << endl; } SomeClass(SomeClass &obj) { { cout<<NumA<<'\t'<<"is Destructor."<<endl; } }; int main() { MyTestClass Myclass1(5), Myclass2.Print(); return 0; } 程序的运行结果为: Myclass2(Myclass1);
,第二行是
A.show( ); } 15 10 三、程序填空题
B.show( );
1、完成如下的类,在横线中填写合适的内容。 #include <iostream> #include <cstring> using namespace std; enum Esex{mid , man , woman};//枚举请自学 2.7 class Person { int Num; //编号 char Name[12]; //姓名 Esex Sex; //性别 float Weight; //体重 public: Person(int , char * , Esex , float); Person(); ~Person() {} void PrintInfo(); int Workdays(); }; Person::Person( { Num = id; int id ,char *name , Esex s , float w)

《C面向对象程序设计答案解析》-第五章谭浩强-清华大学出版社

《C面向对象程序设计答案解析》-第五章谭浩强-清华大学出版社

1:#include <iostream>using namespace std;class Student{public:void get_value(){cin>>num>>name>>sex;}void display( ){cout<<"num: "<<num<<endl;cout<<"name: "<<name<<endl;cout<<"sex: "<<sex<<endl;} private :int num;char name[10];char sex;};class Student1: public Student {public:void get_value_1(){get_value();cin>>age>>addr;}{ cout<<"age: "<<age<<endl; //引用派生类的私有成员,正确。

cout<<"address: "<<addr<<endl;} //引用派生类的私有成员,正确。

private:int age;char addr[30];};int main(){Student1 stud1;stud1.get_value_1();stud1.display();stud1.display_1();return 0;}2:#include <iostream>using namespace std;class Student{public:void get_value(){cin>>num>>name>>sex;}{cout<<"num: "<<num<<endl;cout<<"name: "<<name<<endl;cout<<"sex: "<<sex<<endl;}private :int num;char name[10];char sex;};class Student1: private Student{public:void get_value_1(){get_value();cin>>age>>addr;}void display_1(){display();cout<<"age: "<<age<<endl; //引用派生类的私有成员,正确。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

C程序设计第五章课后习题答案

C程序设计第五章课后习题答案

循环结构程序设计P115 5.1 用while计算1至100的合.#include<stdio.h>int main(){int i=1,sum=0;while(i<=100) //对于需要运算的值,要么在运算前可以赋值,要么一开始要指定.{sum=sum+i;i++;}printf("The sum is %d .\n",sum);return 0;}P117 5.2 用do-while来做1至100的合.#include<stdio.h>int main(){int i=1,sum=0;do// do-while可以做的事,用while都可以做到.{ //do-while先做一次执行,再判断条件,而while却是先做一个条件,再执行.sum=sum+i;i++;}while(i<=100);printf("The sum is %d .\n",sum);return 0;}P118 5.3 比较do-while与while的差别.#include<stdio.h>{int i,sum=0;printf("Please input a number :");scanf("%d",&i); //输入10以内,正常,11的话,则sum仍然是0.while(i<=10){sum=sum+i;i++;}printf("The sum of 1-10 is %d .\n",sum);return 0;}#include<stdio.h>int main(){int i,sum=0;printf("Please input a number :");scanf("%d",&i); //输入10以内,结果一样.输入11的话,先做操作,所以sum=11.do{sum=sum+i;i++;}while(i<=10); //此重点在于理解二者的差别.printf("The sum of 1-10 is %d .\n",sum);return 0;}P126 5.4 break的例子.#include<stdio.h>int main(){int i,b=0,a,c;for(i=0;i<=1000;i++){printf("Please input amount :"); //循环体内套有输出语句以及跳出语句.scanf("%d",&a);b=b+a;if(b>=100)break; //break是用于跳出循环,对if无效,对while for switch 这一类.}}c=b/i;printf("conut is %d , aver is %d ",i+1,c); //注意%号后的形式,否则可能输出错误.return 0;}P127 5.5 continue的例子.#include<stdio.h>int main(){int i;for(i=1;i<20;i++){if(i%3!=0){continue; //跳过本次I,执行下一个i.}printf("%d ",i);}printf("\n");return 0;}P128 5.6 形成一个4*5的矩阵.#include<stdio.h>int main(){int i,j,a=0; //没有给初值,会出现警告: 使用了未初始化的局部变量“a”.for(i=1;i<=4;i++){for(j=1;j<=5;j++,a++) // a用来控制换行.{if(a%5==0){printf("\n");}printf("%d\t",i*j);}}printf("\n");return 0;}P131 5.7 用一个交错的式子求哌的近似值.#include<stdio.h>#include<math.h>int main() //四分之哌等于(1)-(1/3)+(1/5)-(1/7)+(1/9)-(1/11).{float s=1,n=1,m,sum=0,t;for(m=1;;m=m+2) //不确定哪项才会小于等于十的负六次方,所以不指定,无限下去.{ //不指定第二项,执行语句中应该有控制跳出的句子,否则死循环.t=(s)*(n/m); //这是第一项,s是符号,if(fabs(t)<=1e-6) //应该写在这里,题目要求这一项不累加进去.{break;}sum=sum+t; //因为累加项在这里,所以,一旦跳出就不会累加进来了.s=s*(-1); //变号一次.}printf("四分之一哌的值是%f.\n",sum);printf("一个完整哌的值是%f.\n",sum*4);return 0;}//下面这段小代码用来验证关于数值型数据类型的关系.去掉注释,可运行.//如果出现类似值为全1或是全零的话,一般可以考虑数据类型赋值或是定义错了的问题.//#include <stdio.h> //这是关于int float double三者关复杂关系的,乱啊,如果看不懂,可以通过实验自己明白来.////int main() //在C语言中,1.0认为是实数,即是double型,所以,如果你把它用float输出的话,会有警告:警告 1 warning C4305: “=”: 从“double”到“float”截断.//{// float m,a,b,c; //一旦定义了是这种类型的话,输出或是赋值的时候只能扩展不能截断,意思就是能变成double型,不能变成int型啦.而且后面的赋值会跟着它变成相应的类型.比如下面的m=1,其实得到的是m=1.0.// int d,e,f;// m=1;// a=1.0/3;// b=1/3;// c=m/3;// d=1.0;// e=1/4;// f=1.0/4;// printf("%lf(float用double的%lf来输出是可以的.)\n%f\n%f\n%f\n",m,a,b,c); //不管上面定义什么,这边写的输出类型是什么,就按相应的类型输出,有可能会出错,所以建议按定义的类型来输出.当然扩展的是不会错的,截断的是会错的,比如float可以用%lf来输出,而不能用%d来输出.// printf("%d\n%d\n%d\n",d,e,f); //但是,不相应的int型不可以用%f来输出的.因为int float就不同种类,一个是整数,一个是小数,float double同样是有小数点的!!!!// return 0;//}#include<stdio.h>int main() //这个就是著名的Fibonacci(费波那契数列问题){int f1=1,f2=1,f3,i;printf("%12d\n%12d\n",f1,f2);for(i=1;i<=38;i++) //注意,这是个基础问题,(i=1;i<=5;i++)这里其实进行了次运算,因为有f1,f2,要求有个,所以要有个.要么写<=38,要么写<39,边界问题一定要注意,不可以太随意!!!!{f3=f1+f2;printf("%12d\n",f3); //这个问题同样适用于"一对兔子一个月生一对"的问题.,f1=f2; //f1=f1+f2;此时它们各是,所以,现在的f1是.f2=f3; //f2=f2+f1;此时的f1已经是最先二者之和了.可以不用到f3.}return 0;}#include<stdio.h>#include<math.h>int main(){double num;int i;printf("Please input a number :");scanf("%lf",&num); //因为sqrt要求是浮点型,那就给它浮点型,需要时再强制转换.for(i=2;i<=sqrt(num);i++) //这边是<=号没错.{if((int)num%i==0) //如果在这期间有任何一个可以为零的话,则不是素数.{break; //当然跳出.}} //执行到这里的时候,i=5,已经变成了!!if(i<=sqrt(num)){printf("Not %d",(int)num);}else//如上所述,i=5,超出了求根的值,所以是素数.{printf("Yes %d",(int)num);}return 0;}P137 5.10 求100至200间的素数.#include<stdio.h>//不解释,HOHO>>>>...#include<math.h>int main(){double j;int i,k=0;for(j=100;j<=200;j++){for(i=2;i<=sqrt(j);i++){if((int)j%i==0){break;}}k=k+1; //这里是布局的开头.学习一下,有助逻辑.if(i<=sqrt(j)){printf("Not %d ",(int)j);if(k%5==0) //5个换一次行.{printf("\n");}}else{printf("Yes %d ",(int)j);if(k%5==0){printf("\n");}}}return 0;}P139 5.11 密码转换.#include<stdio.h>int main(){char c;c=getchar();while(c!='\n') //这也可以用数组来实现.{if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){if((c>='w'&&c<='z')||(c>='W'&&c<='Z')){c=c-22;}else{c=c+4;}printf("%c",c);c=getchar(); //套在循环里,依次得到字母,而while中判断回车为结束.}}printf("\n"); //这是布局问题.return 0;}P140 0.3 最大公约数和最小公倍数.#include<stdio.h>//最大公约数用累除法,除到无余数时的被除数是最大公约数.main (){int m, n, c, d;int gcd(); //这是最大公约数的缩写,此处调用函数,可以不写里面的实参.int lcm(); //这是最小公倍数的缩写,此处调用函数,可以不写里面的实参.printf("Please input two number :\n");scanf("%d %d",&m,&n);c=gcd(m,n); //c获取最大公约数d=lcm(m,n); //d获取最小公倍数printf("The GCD of %d and %d is : %d !\n", m, n, c);printf("The LCM of %d and %d is : %d !\n", m, n, d);return 0;}int gcd(int x, int y) //最大公约数Greatest Common Divisor{int temp;while(x%y!=0){temp=y; //y在下一轮中作为除数,即是下一轮中的X,所以先闪一边去.y=x%y; //x,y的余数作为下一轮中的Y,由x%y来取得.x=temp; //刚才temp中存储了y的值,现在拿出来作为下一轮中的X使用.}return y; //这是每一轮中的被除数,按原理来,这就是最大公约数,即累除法的原理. }int lcm(int x, int y) //最小公倍数Lowest Common Multiple{int i, temp;if(x<y) //此段代码结果是保证二者大的数在X上,小的数在Y上.即小于号降序.{ //以下为经典三行码,实现两个数的互换.temp=x;x=y;y=temp;}for(i=1; i<=y; i++) //设定一个区间,从1至大的数之间的循环.{if(!((x*i)%y)) //此式子如有余数,加上"!"号,会是假,则不返回,进行下一轮.{ //如此往复,直到取模无余数,那么小的数X乘以区间当前的I值,就是最小公倍数.return x*i;}}}P140 0.4 判断一串输入的字符.#include<stdio.h>int main(){char ch;int a=0,b=0,c=0,d=0,e=0;printf("Please input the string\n");while((ch=getchar())!='\n') //直到回车.{if(ch<='z'&&ch>='a'){a++;}else if(ch==' '){c++;}else if(ch<58&&ch>47){d++;}else if(ch<='Z'&&ch>='A'){b++;}else{e++;}}printf("大写%d 小写%d 空格%d 数字%d 其它%d\n",a,b,c,d,e);}#include<stdio.h>//不理解时可以百度或是谷歌更多的信息.int main() //想办法既快速做完,又要消化理解!!!{int temp,i,a,n,sum=0; //主逻辑,友好性暂时放松.scanf("%d %d",&a,&n); //a是数字,n是要乘的个数.temp=a; //先把第一阶的值存起来.for(i=0;i<n;i++){sum=sum+a;printf("%d + ",a); //事关布局.a=a*10+temp; //重点是每次乘,然后加上上一个数.}printf("= %d .",sum);return 0;}P140 0.6 1!+2!+3!+4!.....的值. #include<stdio.h>int main() //1!+2!+3!+4!.....{int i,j,k,sum=0,m=1;scanf("%d",&k); //比如设定为,值为.for(i=1;i<=k;i++) //第一层循环,指定到.{for(j=1;j<=i;j++) //第二层循环,指定至当前数.{m=m*j;} //到此是阶乘的结构.sum=sum+m;m=1;}printf("%d",sum); //完全不理解时,搜索并参考.return 0; //尝试自己做,第一次做出来就是自己的东西了. }#include<stdio.h>int main(){int a,b;double c,asum=0,bsum=0,csum=0;for(a=1;a<=100;a++) //三个块分别注释验证结果.{asum=asum+a;}for(b=1;b<=50;b++) //在VS运行中,注意*.cpp为C++语言.{bsum=bsum+b*b; //为了避免语言差别,请注意文件名为*.c.}for(c=1;c<=10;c++) //c作浮点运算,所以定义在double类型中.{csum=csum+1/c;}printf("%lf",asum+bsum+csum);return 0;}PP#include<stdio.h>#include<math.h>int main(){int j,k,s[6],x=100,y,sum=0;for(j=153;j<=154;j++){for(k=2;k>=0;k--){s[k]=j%(int)pow(10,k+1)/(int)pow(10,k);y=pow(s[k],3);sum+=y;printf("%d-%d--%d\t",k,s[k],j);}printf("%d\n",sum);}return 0;}P140 0.8 水仙花数.//#include <stdio.h> //一步步的发现问题.////int main() //在%和/号之间,以前pow.以后再做.//{// int i,j,k,a,b,c,sum=0; //这里逻辑对,算出来却错了.// for(i=2;i<=4;i++) //计算机在想什么,看来它的大脑难以模拟.// {// for(j=pow(10,i);j<=pow(10,i+1)-1;j++) //我不完全明白它遵守的逻辑. // {// for(k=0;k<=i;k++)// {// sum+=pow((j%pow(10,i+1)/pow(10,i)),3);// }// if(sum==j)// {// printf("%d 是水仙花数!\n",j);// }// sum=0;// }// }// return 0;//} //为什么还是无法实现?!#include<stdio.h>#include<math.h>int main(){int a,b,c,i,sum=0; //这里只计算三位数的.for(i=100;i<1000;i++){a=i/100;b=i%100/10;c=i%10;sum+=a*a*a+b*b*b+c*c*c;if(sum==i){printf("%d 是水仙花数.\n",i);}sum=0;}return 0;}P141 0.9 完数.#include<stdio.h>int main(){int i,j,r;for(i=1;i<=1000;i++) //零是个临界值,不能包括它.{r=0; //每次清零重来.类似水仙中的sum.for(j=1;j<i;j++){if(i%j==0) //除得尽即是因子.{r=r+j; //然后累加进去.}}if(r==i) //若相等.{printf("%d 是完数.\n",i);}}return 0;}P141 0.10 2/1+3/2+5/3+8/5+13/8…#include<stdio.h>int main() //10.007051{double i,a=2,b=1,c,s=0; //a是分子,b是分母.for(i=0;i<6;i++) //二十可以用户指定.{s+=a/b; //中间储值变量.c=a+b;b=a;a=c;}printf("%lf\n",s);return 0;}#include<stdio.h>int main() //从一百开始,减一半再自加两次,下降一次,反弹一次.{double sum=100,high=100,up,donw,i;for(i=1;i<10;i++) //不管指定到哪个数,都不会超过三百.{up=high/2;donw=up;high=donw; //自咬尾巴问题.sum+=donw*2;}printf("%lf %lf\n",donw,sum);return 0;}P141 0.12 猴子吃桃子.#include<stdio.h>int main() //从一百开始,减一半再自加两次,下降一次,反弹一次.{int i,sum=1;for(i=1;i<=10;i++) //临界要清楚,结果要与手算的前几个实例相匹配.{printf("倒数第%d天还剩有%d个桃子.\n",i,sum);sum=(sum+1)*2;}//printf("%d\n",sum);return 0;}#include<stdio.h>#include<conio.h>main() //只关注左半部分.右半部分无视空格.{int i,j,k,m=6; //m可指定,指定中心点位置.可任意奇偶.for(i=1;i<=m;i++) //上半部分.其实也是正三角.{for(j=1;j<=m-i;j++) //一到中心点前i个位置填充空格.printf(" ");for(k=1;k<2*i;k++) //空格后向前填充星号的个数.是奇数.一,三,五... printf("*");printf("\n");}for(i=m-1;i>0;i--) //下半部分.其实也是倒三角.{ //减一是因为行数问题.这是中心行以下的.for(j=m-1;j>=i;j--)printf(" ");for(k=1;k<2*i;k++)printf("*");printf("\n");}getch(); //用户反应后结束.但,没必要.}。

最新c语言第五章选择结构程序设计(习题册答案)

最新c语言第五章选择结构程序设计(习题册答案)

最新c语⾔第五章选择结构程序设计(习题册答案)第五章选择结构程序设计基础练习(A)⼀、填空题1、关系表达式的运算结果是逻辑值。

C语⾔没有逻辑型数据,以1代表“真”,以0代表“假”。

2、逻辑运算符!是单⽬运算符,其结合性是由右结合性。

3、C语⾔提供的三种逻辑运算符是&&、|| 、!。

其中优先级最⾼的为!,优先级最低的为| | 。

4、逻辑运算符两侧的运算对象不但可以是0和1,或者是0和⾮0的整数,也可以是任何类型的数据。

系统最终以0 和⾮0 来判定它们属于“真”或“假”。

5、设y为int型变量,请写出描述“y是偶数”的表达式(y%2==0)。

6、设x,y,z均为int型变量,请写出描述“x或y中有⼀个⼩于z”的表达式x7、条件“22&&x<3。

8、判断char型变量ch是否为⼤写字母的正确表达式是(ch>=‘A’)&&(ch<=‘Z’)。

9、当a=3,b=2,c=1时,表达式f=a>b>c的值是0。

10、当a=5,b=4,c=2时,表达式a>b!=c的值是1。

11、已知A=7.5,B=2,C=3.6,表达式A>B&&C>A||AB的值是0。

12、若a=6,b=4,c=2,则表达式!(a-b)+c-1&&b+c/2的值是1。

13、有int x,y,z;且x=3,y=-4,z=5,则表达式(x&&y)==(x||z)的值为1。

14、有int x,y,z;且x=3,y=-4,z=5,则以下表达式的值为1。

!(x>y)+(y!=z)||(x+y)&&(y-z)15、有int a=3,b=4,c=5,x,y;,则以下表达式的值为0。

!(x=a)&&(y=b)&&016、if (!k) a=3;语句中的!k可以改写为k= =0,使其功能不变。

C语言程序设计教程第五章练习题题目

C语言程序设计教程第五章练习题题目

单选题1、关于数组的定义与初始化,下列哪一项是错误的()A.int arr[5] = {1,2,3,4,5};B.int arr[] = {1,2,3,4,5};C.int arr[5] = {1,2,3};D.int arr[5] = {1,2,3,4,5,6};2、在定义数组int arr[10]后,下列选项中对arr的引用正确的是()A.arr[10]B.arr[6.3]C.arr(6)D.arr[0]3、在C语言中,引用数组元素时,其数组下标的数据类型允许是()4、若int arr[5] = {1,2,3}; 则arr[2]的值为()5、在执行int arr[][3] = {1,2,3,4,5,6}:语句后,arr[1][0]的值为()6、关于二维数组,下列选项能正确定义并赋初值的是()A.int n = 5,b[n][n];B.int a[1][2] = {{1},{3}};C.int c[2][] = {{1,2},{3,4}};D.int a[3][2] = {{1,2},{3,4}};7、阅读下列程序段:char s[18] = "a book!";printf("%.4s\n", s);其输出结果为()A.a book!B.a bookC.a bo8、阅读下列程序:int a[4][4] = { { 1, 3, 5, }, { 2, 4, 6 }, { 3, 5, 7 } };printf("%d%d%d%d\n", a[0][0], a[1][1], a[2][2], a[3][3]);正确的输出结果为()9、阅读下面程序:int i;int x[4][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };for (i = 0; i<4; i++)printf("%3d", x[i][3 - i]);下列选项中哪一项是正确的输出结果()A.1 5 9 13B.1 6 11 16C.4 7 10 13D.4 8 12 1610、下列描述中不正确的是()。

visualc程序设计应用教程习题答案郭力子第5章面向对象编程基础

visualc程序设计应用教程习题答案郭力子第5章面向对象编程基础
构造函数不能有返回值。可以有零个或多个参数。
类的对象被撤销时,将自动调用析构函数。一些善后工作 可放在析构函数中完成。析构函数的名字为类名前面加一 个“~”符号,无返回类型,也无参数。
构造函数和析构函数的执行是无条件的,在声明一个对象 或销毁一个对象时,如果没有声明相应的构造函数和析构 函数,系统会自动为之产生,并在创建对象时调用构造函 数,而在销毁对象时调用析构函数
例:简单表达类A中的属性myProperties的声明:
class A {
private int i;
public int myProperties {
get {
//get访问器
return i;
}
set {
//set访问器
i=value;
}
}
}
6/1
《 Visual C#程序设计应用教程》
尚 辅 网 shangfuwang
果用上面的构造函数去构建了一个目标对象,则this便可以 用来代表所构建的对象。this用在构造函数中时,便于区别 同名的构造函数参数和类成员变量。
6/1
《 Visual C#程序设计应用教程》
尚 辅 网 shangfuwang
5.2.6 类的继承
继承允许在已有类的基础上创建新类,新类从已有类中继承类 成员,而且可以重新定义或增加新的成员,从而形成类的层 次或等级。
尚 辅 网 shangfuwang
set访问器:给属性赋值时使用,set访问器始终使用隐含的 参数value设置属性的值。获取属性值时使用get访问器。
get访问器:通过return返回属性的值。如果只有get访问 器,表示是只读属性;如果只有set访问器,表示只写属 性;如果既有get也有set访问器,表示读写属性。

(完整)C++面向对象程序设计习题 类与对象

(完整)C++面向对象程序设计习题 类与对象

类和对象(一)知识点:1.类与对象的概念,及两者的关系?2.类定义的格式,对象定义的格式,访问对象的成员的格式3.类中成员访问权限有哪几种,它们的特点?4。

如何对对象进行初始化?5。

构造函数与析构函数的特点,构造函数在哪些情况下被系统自动调用,析构函数什么情况下被调用;存在虚基类的派生类构造函数调用顺序?6.缺省构造函数的特点7。

拷贝构造函数的功能与特点8。

成员函数与内联函数的区别9.静态成员的概念与作用10.静态成员函数调用格式11.什么是友元,友元的作用12.作用域运算符的功能是什么?它的使用格式如何?13.满足成员函数重载的条件作业题一、选择填空1.在下列关键字中,用以说明类中公有成员的是( )。

A . public; B.private; C.protected; D.friend。

2.下列的各类函数中,( )不是类的成员函数.A.构造函数; B.析构函数; C.友员函数; D.拷贝初始化构造函数。

3.作用域运算符的功能是( )。

A.标识作用域的级别的;B.指出作用域的范围的;C.给出作用域的大小的;D.标识某个成员是属于哪个类的。

4.( )是不可以作为该类的成员的.A.自身类对象的指针;B.自身类的对象;C.自身类对象的引用;D.另一个类的对象。

5.( )不是构造函数的特征。

A.构造函数的函数名与类名相同;B.构造函数可以重载;C.构造函数可以重载设置缺省参数;D.构造函数必须指定类型说明。

6.()是析构函数的特征。

A.一个类中能定义一个析构函数;B.析构函数名与类名不同;C.析构函数的定义只能在类体内;D.析构函数可以有一个或多个参数。

7.通常的拷贝初始化构造的参数是()。

A.某个对象名;B.某个对象的成员名;C.某个对象的引用名;D.某个对象的指针名。

8.关于成员函数特征的下述描述中,( )是错误的。

A.成员函数一定是内联函数;B.成员函数可以重载;C.成员函数可以设置参数的缺省值;(只能一次)D.成员函数可以是静态的。

《C面向对象程序设计答案解析》-第五章谭浩强-清华大学出版社.docx

《C面向对象程序设计答案解析》-第五章谭浩强-清华大学出版社.docx

1:#include <iostream>using namespace std;class Student{public:void get_value(){cin>>num>>name>>sex;}void display( ){cout<<"num: "<<num<<endl;cout<<"name: "<<name<<endl;cout<<"sex: "<<sex<<endl;} private :int num;char name[10];char sex;};class Student1: public Student {public:void get_value_1(){get_value();cin>>age>>addr;}void display_1(){cout<<"age: "<<age<<endl;// 引用派生类的私有成员,正确。

cout<<"address: "<<addr<<endl;}// 引用派生类的私有成员,正确。

private:int age;char addr[30];};int main(){Student1 stud1;stud1.get_value_1();stud1.display();stud1.display_1();return 0;}2:#include <iostream>using namespace std;class Student{public:void get_value(){cin>>num>>name>>sex;}void display( ){cout<<"num: "<<num<<endl;cout<<"name: "<<name<<endl;cout<<"sex: "<<sex<<endl;}private :int num;char name[10];char sex;};class Student1: private Student{public:void get_value_1(){get_value();cin>>age>>addr;}void display_1(){display();cout<<"age: "<<age<<endl;// 引用派生类的私有成员,正确。

C++程序设计(第2版)课后第五章习题解答

C++程序设计(第2版)课后第五章习题解答

答案:(1)类型
(2)数量
(3)下标运算符
(4)下标
(5)索引
(6)常变量
5.1.2 C/C++中的多维数组用的是一个的定义,即多维数组的基本定义是成的数组,三维数组的元素是 (3) 。
答案:(1)嵌套
(2)以数组作为元素
(3)二维数组
5.1.3 计算机内存是一维编址的,多维数组在内存中的存储 (1) ,C/C++多维在内存中
第五章 数组与指针习题 1
第五章 数组与指针习题填充题
5.1.1 数组定义时有三个要素:数组名,数组元素的和数组元素的。按元
素在数组中的位置进行访问,是通过 (3) 进行的,称为 (4) 或 (5) 访问。
为了使数组声明中数组的大小修改更为方便,总是将 (6) 用于声明数组长度。
5.1.4 的大小是确定的,所谓“不检查数组边界”只是不检查
的边界,而 (3) 的边界是在控制之中的,所以多维数组名作为函数的参数只可以
(4) 缺省。
答案:(1)较低各维的
(2)最高维(第一维)
(3)较低各维
(4)最高维
5.1.5 指针变量保存了另一变量的值,不可以任意给指针变量赋一个地址值,只能赋
给它 (2) 和 (3) 的地址。使用变量名来访问变量,是按 (4) 来直接存取变
量称为 (5) 方式;而借助指针变量取得另一变量的地址,访问该变量称为 (6) 方式。
答案:(1)地址
(2)NULL
的排列是 (2) 方式,即越 (3) 的下标变化 (4) 。设数组a有m行n列,每
个元素占内存u个字节,则a[i][j]的首地址为 (5) + (6) 。

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

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

Chapter 5Functions for All Subtasks1. Solutions to Selected Programming ProjectsDetailed solutions to the first 6 projects are presented here. The rest are essentially thesame problems, except for what is being converted. Notes about the remaining problemsare included.One of the more important things in programming is planning, even for the simplest program. If the planning is thorough, the coding will be easy, and the only errors likely tobe encountered are syntax errors, usually caused by either typing errors, a boundary condition problem (frequently, an off by one error), or (we hope not) lack of knowledge of the language details.1 Convert TimeTask: Convert 24 hour time notation to 12 hour AM/PM notation. General comments: The student should note that:a) The convert function has boundary cases that require careful attention.b) ALL of this commentary and planning should be done PRIOR to beginning to write the program. Once this is done the program is almost written. The sooner coding begins, the longer the program will take to do correctly.c) When testing for equality, as inif (12 == hours)put the constant first. The compiler will catch errors such as if (12= hours) which are hardto see otherwise. I made many errors of this type while coding this problem.1//file: //Task: Convert 24 hour time notation to 12 hour AM/PM//notation.//Input: 24 hour time//Output: corresponding 12 hour time, with AM/PM indication //Required: 3 functions: input, conversion, and output.// keep AM/PM information in a char variable// allow repeat at user's option//Notes: conversion function will have a char reference// parameter to return whether the time is AM/PM. Other// parameters are required.#include <iostream>using namespace std;void input( int& hours24, int& minutes);//Precondition: input( hours, minutes ) is called with//arguments capable of being assigned.//Postcondition:// user is prompted for time in 24 hour format:// HH:MM, where 0 <= HH < 24, 0 <= MM < 60.// hours is set to HH, minutes is set to MM.//KNOWN BUG: NO CHECKING IS DONE ON INPUT FORMAT. Omitting//the “:” (colon) from the input format “eats” one character //from the minutes data, and silently gives erroneous//results.void convert( int& hours, char& AMPM );//Precondition: 0 <= hours < 24,//Postcondition:// if hours > 12, // Note: definitely in the afternoon// hours is replaced by hours - 12,// AMPM is set to 'P'// else if 12 == hours // boundary afternoon hour // AMPM is set to 'P', // hours is not changed. // else if 0 == hours // boundary morning hour // hours = hours + 12;// AMPM = 'A';// else// (hours < 12)// AMPM is set to 'A';// hours is unchangedvoid output( int hours, int minutes, char AMPM ); //Precondition:// 0 < hours <=12, 0 <= minutes < 60,// AMPM == 'P' or AMPM == 'A'//Postconditions:// time is written in the format// HH:MM AM or HH:MM PMint main(){int hours, minutes;char AMPM, ans;do{input( hours, minutes );convert ( hours, AMPM );output( hours, minutes, AMPM );cout << "Enter Y or y to continue,"<< " anything else quits."<< endl;cin >> ans;} while ( 'Y'== ans || 'y' == ans );return 0;}void input( int& hours24, int& minutes){char colon;cout << "Enter 24 hour time in the format HH:MM "<< endl;cin >> hours24 >> colon >> minutes;}//Precondition: 0 <= hours < 24,//Postcondition:// if hours >= 12,// hours is replaced by hours - 12,// AMPM is set to 'P'// else // (hours < 12)// hours is unchanged and AMPM is set to 'A'void convert( int& hours, char& AMPM ){if (hours > 12) // definitely in the afternoon{hours = hours - 12;AMPM = 'P';}else if (12 == hours) // boundary afternoon hour AMPM = 'P'; // but hours is not changed.else if (0 == hours) // boundary morning hour{hours = hours + 12;AMPM = 'A';}else // (hours < 12) // definitely morning hour AMPM = 'A'; // hours is unchanged}void output( int hours, int minutes, char AMPM ) {cout << "Time in 12 hour format: " << endl<< hours << ":" << minutes << " "<< AMPM << 'M' << endl;}A typical run follows:20:33:03:~/AW$ a.outEnter 24 hour time in the format HH:MM0:30Time in 12 hour format:12:30 AMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MM2:15Time in 12 hour format:2:15 AMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MMEnter 24 hour time in the format HH:MM11:30Time in 12 hour format:11:30 AMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MM12:30Time in 12 hour format:12:30 PMEnter Y or y to continue, anything else quits.yEnter 24 hour time in the format HH:MM23:59Time in 12 hour format:11:59 PMEnter Y or y to continue, anything else quits.n20:33:59:~/AW$2. Time// Waiting time// Problem 2, Savitch, Programming and Problem Solving with C++ 5th //// file ch5.2.cpp// Program input: current time and a waiting time// each time is number of hours and a number of minutes.// Program output is is the time the waiting period completes.// Use 24 hour time. Allow user repeat.// Notes: The 24 hour boundary, i.e., when the time wraps to the// next day is important here.//// Known Bugs: If the completion time would be in a day later// than the next day after the start, this program gives incorrect // results.//#include <iostream>void input( int& hours24, int& minutes){using std::cout;using std::cin;using std::endl;char colon;cout << "Enter 24 hour time in the format HH:MM "<< endl;cin >> hours24 >> colon >> minutes;}void output( int hours, int minutes){using std::cout;using std::cin;using std::endl;cout << "Time in 24 hour format:\n"<< hours << ":" << minutes << endl;}int main(){using std::cout;using std::cin;using std::endl;int timeHours, timeMinutes, waitHours, waitMinutes,finishHours, finishMinutes;cout << "Compute completion time from current time and waiting period\n";char ans = 'y';while ('y' == ans || 'Y' == ans){cout << "Current time:\n";input(timeHours, timeMinutes);cout << "Waiting time:\n";input(waitHours, waitMinutes);finishHours = timeHours + waitHours;finishMinutes = timeMinutes + waitMinutes;finishHours += finishMinutes / 60;if(finishHours >= 24){finishHours %= 24;cout << "Completion time is in the day following the start time\n";}finishMinutes%= 60;cout << "Completion ";output(finishHours, finishMinutes);cout << "\n\nEnter Y or y to continue, any other halts\n\n";cin >> ans;}return 0;}/*Typical runCompute completion time from current time and waiting period Current time:Enter 24 hour time in the format HH:MM12:30Waiting time:Enter 24 hour time in the format HH:MM15:40Completion time is in the day following the start timeCompletion Time in 24 hour format:4:10Enter Y or y to continue, any other haltsyCurrent time:Enter 24 hour time in the format HH:MM8:30Waiting time:Enter 24 hour time in the format HH:MM15:10Completion Time in 24 hour format:23:40Enter Y or y to continue, any other haltsnPress any key to continue*/3. Project 3 Modify project 2 to use 12 hour time.We provide suggestions on how to proceed in solving this problem.This problem is different from #2 only in the details of managing 12 hour time. The wait time interval could be any number of hours and minutes, so the output should provide the number of days that elapse from the start time until completion.You may want an input routine that verifies that you have entered legitimate 12 hour time data, i.e. hours betwee 1 and 12, minutes between 0 and 59, and includes either an A for AM or a P for PM.Write code to convert the 12 hour start time to 24 hour time and use the code from #3 to computer the finish time.Decide on how to handle finish times that fall in some later day, then convert 24 hour time to 12 hour time and output that using code from #2.4. StatisticsCompute average and standard deviation of 4 entries.General remarks are in the code file which I present here:// file #include <iostream>using namespace std;/*Task: Write a function that computes average (I will callthis the arithmetic mean or simply the mean) and standard deviation of four scores. The average or mean, avg, is computed asavg = ( s1 + s2 + s3 + s4 ) / 4The standard deviation is computed asstd_deviation = ()()() s a s a s a1234-+-+-where a = avg. Note that some statisticians may wish to use 3 instead of 4. We will use 4.Input: scores s1 s2 s3 s4Output: standard deviation and mean.Required: The function is to have 6 parameters. This function calls two others that compute the mean and the std deviation.A driver with a loop should be written to test the functionat the user's option.*///function declaration (or prototype)//When used, the math library must be linked to the//executable.#include <cmath> // for sqrtusing namespace std;void average (double s1, double s2, double s3,double s4, double& avg){avg = ( s1 + s2 + s3 + s4 ) / 4;}// Preconditions: average function must have been called on//the data, and the value of the average passed into the//parameter a//Postconditions: Standard deviation is passed back in//the variable stdDevvoid sD (double s1, double s2, double s3, double s4,double a, double& stdDev){stdDev = sqrt( (s1 - a)*(s1 - a) + (s2 - a)*(s2 - a)+ (s3 - a)*(s3 - a) + (s4 - a)*(s4 - a) )/4 ; }void statistics( double s1, double s2, double s3, double s4, double& avg, double& stdDev );//Preconditions: this function is called with any set of//values. Very large or very small numbers are subject to//errors in the calculation. Analysis of this sort of error //is beyond the scope of this chapter.//PostConditions: avg is set to the mean of s1, s2, s3, s4//and stdDev is set to the standard deviation of s1..s4//function definition:void statistics( double s1, double s2, double s3, double s4, double& avg, double& stdDev ) {average ( s1, s2, s3, s4, avg );sD ( s1, s2, s3, s4, avg, stdDev );}int main(){double s1, s2, s3, s4, avg, stdDev;char ans;do{cout << "Enter 4 decimal numbers, "<< "I will give you the mean "<< endl<< "and standard deviation of the data " << endl;cin >> s1 >> s2 >> s3 >> s4;statistics( s1, s2, s3, s4, avg, stdDev);cout << "mean of " << s1 << " " << s2 << " " << s3<< " " << s4 << " is " << avg << endl<< "the standard deviation of "<< "these numbers is " << stdDev << endl;cout << "y or Y continues, any other terminates" << endl; cin >> ans;} while ( 'Y' == ans || 'y' == ans );return 0;}A typical run follows:21:44:35:~/AW$ a.outEnter 4 decimal numbers, I will give you the meanand standard deviation of the data12.3 13.4 10.5 9.0mean of 12.3 13.4 10.5 9 is 11.3the standard deviation of these numbers is 0.841873y or Y continues, any other terminatesyEnter 4 decimal numbers, I will give you the meanand standard deviation of the data1 2 3 4mean of 1 2 3 4 is 2.5the standard deviation of these numbers is 0.559017y or Y continues, any other terminatesn21:45:05:~/AW$5. Change maker problem.Only notes on the solution are provided for this problem. In my discussion of this problem, I include a word or two on algorithm development, concluding (sometimes only the following).A greedy algorithm works for this problem. A greedy algorithm makes locally optimal choices at each point in the sequence of points in the solution, in the hope that the locally optimal choices will result in a globally optimal solution. This works surprisingly often, including this problem. It is interesting to me that the greedy algorithm fails for some national coinage.I suggest that the student write code to choose the largest number of coins of the largest denomination from the list of coin not yet used. Repeat this on the remaining amount of money for decreasing denominations until no more coins are left.6. Conversion 1Conversion of feet/inches to meters://File: //Task: Convert feet/inches to meters//Input:a length in feet and inches, with possible decimal//part of inches//Output: a length in meters, with 2 decimal places, which//are the 'centimeters' specified in the problem.//Required: functions for input, computation, and output.//Include a loop to repeat the calculation at the user's//option.Remarks: The computation is a simple conversion from //feet + inches to feet with a decimal part, then to meters. //Output is restricted to 2 decimal places.////By 'meters and centimeters' the author means that the//output is to be meters with two decimal places - which is//meters and centimeters. I mention this because my students //always stumble at this because of a lack of knowledge of //the metric system.#include <iostream>using namespace std;void input ( int& feet, double& inches );//Precondition: function is called//Postcondition://Prompt given to the user for input in the format FF II,//where FF is integer number of feet and II is a double//number of inches. feet and inches are returned as entered //by the user.void convert (int feet, double inches, double& meters );//Preconditions://REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//inches < 12, feet within range of values for int type//Postconditions://meters assigned 0.3048 * (feet + inches/12)//observe that the centimeter requirement is met by//the value of the first two decimal places of the converted //feet, inches input.void output( int feet, double inches, double meters );//input: the formal argument for meters fits into a double//output://"the value of feet, inches" <feet, inches>//" converted to meters, centimeters is " <meters>//where meters is displayed as a number with two decimal//placesint main(){int feet;double inches, meters;char ans;do{input ( feet, inches );convert ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );return 0;}void input ( int& feet, double& inches ){cout << "Enter feet as an integer: " << flush;cin >> feet;cout << "Enter inches as a double: " << flush;cin >> inches;}const double METERS_PER_FOOT = 0.3048;const double INCHES_PER_FOOT = 12.0;void convert (int feet, double inches, double& meters ){meters = METERS_PER_FOOT * (feet +inches/INCHES_PER_FOOT);}void output( int feet, double inches, double meters ) {//inches, meters displayed as a number with two decimal //placescout.setf( ios::showpoint );cout.setf( ios::fixed );cout.precision(2);cout << "the value of feet, inches" << feet << ","<< inches << endl<< " converted to meters, centimeters is "<< meters << endl;}/*A typical run follows:06:59:16:~/AW$ a.outEnter feet as an integer: 5Enter inches as a double: 7the value of feet, inches5,7.00converted to meters, centimeters is 1.70Y or y continues, any other character quitsyEnter feet as an integer: 245Enter inches as a double: 0the value of feet, inches245,0.00converted to meters, centimeters is 74.68Y or y continues, any other character quitsq06:59:49:~/AW$*/7. Conversion 2Conversion of meters back to centimeters.//file: //Task: Convert meters with centimeters (just the decimal//part of meters)to feet/inches////Input: a length in feet and inches, with possible decimal //part of inches//Output: A length measured in feet with any decimal fraction //converted to inches by multiplying by 12. Fractions of an//inch are represented by 2 decimal places.////Required: functions for input, computation, and output.//Include a loop to repeat the calculation at the user's//option.////Remark: The computation is a simple conversion from meters //to feet, inches, where inches has a decimal part.//Output is restricted to 2 decimal places//Comment: Please see Problem 4 for discussion of 'meters and //centimeters'#include <iostream>using namespace std;void input ( double & meters );//Precondition: function is called//Postcondition://Prompt given to the user for input of a number of meters as //a double. input of a double for meters has been acceptedvoid convert (int& feet, double& inches, double meters );//Preconditions:// REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//Postconditions://feet is assigned the integer part of meters (after//conversion to feet units) inches is assigned the//fractional part of feet ( after conversion to inch unitsvoid output( int feet, double inches, double meters );//input: the formal argument for meters fits into a double//output://"the value of meters, centimeters is: " <meters>//" converted to English measure is "//<feet> "feet, " <inches> " inches "//where meters is displayed as a number with two decimal//placesint main(){int feet;double inches, meters;char ans;do{input ( meters );convert ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );return 0;}void input ( double& meters ){cout << "Enter a number of meters as a double \n";cin >> meters;}const double METERS_PER_FOOT = 0.3048;const double INCHES_PER_FOOT = 12.0;void convert (int &feet, double& inches, double meters ){double dfeet;dfeet = meters / METERS_PER_FOOT;feet = int( dfeet );inches = (dfeet - feet)*INCHES_PER_FOOT;}void output( int feet, double inches, double meters ){//meters is displayed as a double with two decimal places //feet is displayed as int, inches as double with two//decimal placescout.setf( ios::showpoint );cout.setf( ios::fixed );cout.precision(2);cout << "The value of meters, centimeters " << endl<< meters << " meters" << endl<< "converted to English measure is " << endl << feet << " feet, " << inches << " inches"<< endl;}/*A typical run follows:07:56:28:~/AW$ a.outEnter a number of meters as a double6.0The value of meters, centimeters6.00 metersconverted to English measure is19 feet, 8.22 inchesY or y continues, any other character quitsyEnter a number of meters as a double75The value of meters, centimeters75.00 metersconverted to English measure is246 feet, 0.76 inchesY or y continues, any other character quitsq07:56:40:~/AW$*/8. Conversion 3This exercise combines the two previous exercises. Convert between feet/inches and meters. The direction is the user's option.// file: //Task: Convert between meters and feet/inches at user's//option Within conversion, allow repeated calculation//after end of either conversion, allow choice of another //conversion.//Input: At program request, user selects direction of//conversion. Input is either feet/inches(with decimal//fraction for inches) OR meters with 2 place decimal//fraction that represents the centimeters.//Output: Depends on user selection: either meters or//feet and inches.//Method: Suggested by problem statement: use if-else//selection based on the user input to choose between//functions written for problems 4 and 5 above.//Required: functions for input, computation, and output. //Include a loop to repeat the calculation at the user's //option.#include <iostream>using namespace std;void inputM ( double& meters );//Precondition: function is called//Postcondition://Prompt given to the user for input of a number of meters //as a doublevoid inputE ( int& feet, double& inches );//Precondition: function is called//Postcondition://Prompt given to the user for input in the format FF II,//where FF is an int number of feet and II is a double number //of inches feet and inches are returned as entered by the//user.void convertEtoM (int feet, double inches,double& meters );//Preconditions://REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//inches < 12, feet within range of values for an int//Postconditions://meters assigned 0.3048 * (feet + inches/12)//Observe that the requirement to produce centimeters is met //by the value of the first two decimal places of meters.void convertMtoE (int& feet, double& inches,double meters );//Preconditions:// REQUIRED CONSTANTS: INCHES_PER_FOOT, METERS_PER_FOOT//Postconditions://the variable feet is assigned the integer part of//meters/METERS_PER_FOOT//the variable inches is assigned the fractional part of//feet after conversion to inch units.void output( int feet, double inches, double meters );//input: the formal argument for meters fits into a double//output://"the value of feet, inches" <feet, inches>//" corresponds to meters, centimeters is " <meters>//where meters is displayed as a number with two decimal//placesvoid EnglishToMetric ();// requests English measure, converts to metric, outputs bothvoid MetricToEnglish();// request metric measure, converts to English, outputs bothint main(){char ans;do{int which;cout << "Enter 1 for English to Metric or " << endl<< "Enter 2 for Metric to English conversion"<< endl;cin >> which;if ( 1 == which )EnglishToMetric();elseMetricToEnglish();cout << "Y or y allows another choice of conversion. "<< "any other quits" << endl;cin >> ans;} while ( 'y' == ans || 'Y' == ans );return 0;}void MetricToEnglish(){int feet;double inches, meters;char ans;do{inputM ( meters );convertMtoE ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );}void EnglishToMetric (){int feet;double inches, meters;char ans;do{inputE ( feet, inches );convertEtoM ( feet, inches, meters );output ( feet, inches, meters );cout << "Y or y continues, any other character quits "<< endl;cin >> ans;} while ( 'Y' == ans || 'y' == ans );}void inputE ( int& feet, double& inches ){cout << "Enter feet as an integer: " << flush;cin >> feet;cout << "Enter inches as a double: " << flush;cin >> inches;}void inputM ( double& meters ){cout << "Enter a number of meters as a double " << endl;cin >> meters;}const double METERS_PER_FOOT = 0.3048;const double INCHES_PER_FOOT = 12.0;// convert English measure to Metricvoid convertEtoM (int feet, double inches, double& meters ) {meters = METERS_PER_FOOT * (feet +inches/INCHES_PER_FOOT);}// convert Metric to English measurevoid convertMtoE (int &feet, double& inches,double meters ){double dfeet;dfeet = meters / METERS_PER_FOOT;feet = int( dfeet );inches = (dfeet - feet)*INCHES_PER_FOOT;}void output( int feet, double inches, double meters ){// meters is displayed as a double with two decimal// places// feet is displayed as int, inches as double with two //decimal placescout.setf( ios::showpoint );cout.setf( ios::fixed );cout.precision(2);cout << meters << " meters "<< "corresponds to "<< feet << " feet, " << inches << " inches"<< endl;}/*A typical run follows08:59:38:~/AW$ a.outEnter 1 for English to Metric orEnter 2 for Metric to English conversion2Enter a number of meters as a double7575.00 meters corresponds to 246 feet, 0.76 inchesY or y continues, any other character quitsnY or y allows another choice of conversion. any other quits yEnter 1 for English to Metric orEnter 2 for Metric to English conversion1Enter feet as an integer: 246Enter inches as a double: 0.7675.00 meters corresponds to 246 feet, 0.76 inchesY or y continues, any other character quitsqY or y allows another choice of conversion. any other quitsq09:00:08:~/AW$*/9-12. More Conversions—No Solutions Provided.These problems differ from problems whose solutions have already been presented only in the names and specific factors used to carry out the conversions.13. The Area of an Arbitrary TriangleI provide only notes for this problem.To determine the area of an arbitrary triangle can be computed using Hero’s formula for the area of a triangle1 the lengths of the edges of which are a, b, and c:s = (a + b + c)/2area = sqrt(s(s - a)(s - b)(s - c))It is necessary to test whether edges of lengths a, b and c actually form a triangle. The test for values of a, b and c to form a triangle is that each of the following inequalities be satisfied.a +b > c1 Hero, Heron, or Hron, was a mathematician conjectured to have lived between the 3rd and 2nd centuries BCE. He lived in Alexandria, but wrote in Greek. This formula is ascribed to him as is Hero’s engine, where steam recoil rotates a sphere or wheel.。

《C++程序设计》课后习题参考答案

《C++程序设计》课后习题参考答案

《C++程序设计》课后习题参考答案C++作为一种广泛使用的编程语言,其课后习题对于学习者巩固知识、提高编程能力具有重要意义。

以下是对一些常见课后习题的参考答案。

一、基础概念题1、简述 C++中变量的定义和声明的区别。

变量的定义会为变量分配存储空间,并且可以进行初始化操作。

而变量的声明只是告诉编译器变量的存在以及其类型,但不会为其分配存储空间。

例如:```cppint a = 5; //这是变量的定义,为 a 分配空间并初始化为 5extern int b; //这是变量的声明,说明 b 是一个在其他地方定义的整数变量```2、解释 C++中指针和引用的区别。

指针是一个变量,它存储了另一个变量的地址。

可以通过解引用指针来访问指向的变量。

引用则是给一个已存在的变量起了一个别名,对引用的操作实际上就是对被引用的变量的操作。

指针可以为空,引用不能为空且必须在定义时初始化。

例如:```cppint p = NULL; //合法的指针,可为空int& r = a; //引用必须初始化```二、程序结构题1、编写一个 C++程序,计算 1 到 100 的整数之和。

```cppinclude <iostream>int main(){int sum = 0;for (int i = 1; i <= 100; i++){sum += i;}std::cout <<"1 到 100 的整数之和为:"<< sum << std::endl;return 0;}```2、用 C++实现一个函数,判断一个整数是否为素数。

```cppinclude <iostream>bool isPrime(int num) {if (num < 2) {return false;}for (int i = 2; i i <= num; i++){if (num % i == 0) {return false;}}return true;}int main(){int num;std::cout <<"请输入一个整数:";std::cin >> num;if (isPrime(num)){std::cout << num <<"是素数" << std::endl;} else {std::cout << num <<"不是素数" << std::endl;}return 0;}```三、数组与字符串题1、编写一个 C++程序,将一个整数数组中的元素逆序排列。

面向对象程序设计 C 山师 第五章习题答案

面向对象程序设计 C    山师 第五章习题答案

第五章习题答案一、选择填空1、A2、D3、B4、D5、D6、C7、C8、D9、C 10、A 11、B 12、C13、A 14、D 15、C二、判断下列描述的正确性,对者划√,错者划×。

1、√2、√3、×4、√5、√6、√7、×8、×9、× 10、×11、× 12、√ 13、√ 14、√ 15、× 16、√ 17、× 18、× 19、√ 20、√三、分析下列程序的输出结果。

1、运行该程序输出如下结果。

5811142、运行该程序输出如下结果。

253、该程序输出如下结果。

10+2+1=1320+2+2=2430+2+3=3540+2+4=464、运行该程序的输出结果如下所示。

6,115、运行该程序输出如下结果。

5!+4!+3!+2!+1!=1536、运行该程序输出如下结果。

6,6,67、运行该程序输出如下结果。

sum 1=13sum 2=18sum 3=238、运行该程序输出如下结果。

7209、运行该程序输出如下结果:a=5,b=8a=8,b=510、运行该程序输出结果如下所示。

1011、运行该程序输出结果如下所示。

ff(double):88.18ff(int):9712、运行该程序输出结果如下所示。

1121231234四、按下列要求编程,并上机验证。

1、分析:该程序有3个函数:main(),sum()和average()。

主函数main()中包含有如下操作:输入15个浮点数放在一个数组中,使用循环语句从键盘上输入值,接着分别调用sum()函数求15个浮点数之和,调用average()函数求15个浮点数的平均值,最后将15个浮点数的和值与平均值输出显示。

程序如下:#include <iostream.h>double s, sum(double b[],int n),average(int n)。

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