C++程序设计(第2版 谭浩强)习题答案

C++程序设计习题答案

第2章

8.#include

using namespace std; int main()

{char c1='C', c2='h', c3='i', c4='n', c5='a'; c1+=4; c2+=4; c3+=4; c4+=4; c5+=4;

cout<<\ return 0; }

第3章

2.#include

#include using namespace std; int main ( )

{float h,r,l,s,sq,vq,vz;

const float pi=3.1415926; cout<<\ cin>>r>>h; l=2*pi*r; s=r*r*pi; sq=4*pi*r*r;

vq=3.0/4.0*pi*r*r*r; vz=pi*r*r*h;

cout<

cout<<\ cout<<\ cout<<\ cout<<\ cout<<\ return 0; }

3.#include

using namespace std; int main () {float c,f;

cout<<\请输入一个华氏温度:\ cin>>f;

c=(5.0/9.0)*(f-32); //注意5和9要用实型表示,否则5/9值为0 cout<<\摄氏温度为:\ return 0; };

4.#include

using namespace std; int main ( ) {char c1,c2;

cout<<\请输入两个字符c1,c2:\

c1=getchar(); //将输入的第一个字符赋给c1 c2=getchar(); //将输入的第二个字符赋给c2 cout<<\用putchar函数输出结果为:\ putchar(c1); putchar(c2); cout<

cout<<\用cout语句输出结果为:\ cout<

9.第一种:#include

using namespace std; int main ( ) {int a,b,c;

cout<<\ cin>>a>>b>>c; if(a

cout<<\ else

cout<<\ else if (a

cout<<\ else

cout<<\ cout<

第二种:#include using namespace std; int main ( )

{int a,b,c,temp,max ;

cout<<\ cin>>a>>b>>c;

temp=(a>b)?a:b; /* 将a和b中的大者存入temp中 */

max=(temp>c)?temp:c; /* 将a和b中的大者与c比较,最大者存入max */ cout<<\ return 0; }

10.#include

using namespace std; int main ( ) {int x,y;

cout<<\ cin>>x;

if (x<1) {y=x;

cout<<\ }

else if (x<10) // 1≤x<10 {y=2*x-1;

cout<<\ }

else // x≥10 {y=3*x-11;

cout<<\ } cout<

11.#include

using namespace std; int main () {float score; char grade;

cout<<\ cin>>score;

while (score>100||score<0)

{cout<<\ cin>>score; }

switch(int(score/10)) {case 10:

case 9: grade='A';break; case 8: grade='B';break; case 7: grade='C';break; case 6: grade='D';break; default:grade='E'; }

cout<<\ return 0; }

12.#include

using namespace std; int main () {long int num;

int indiv,ten,hundred,thousand,ten_thousand,place;

/*分别代表个位,十位,百位,千位,万位和位数*/ cout<<\ cin>>num; if (num>9999) place=5; else if (num>999) place=4; else if (num>99) place=3; else if (num>9) place=2; else place=1;

cout<<\ //计算各位数字

ten_thousand=num/10000;

thousand=(int)(num-ten_thousand*10000)/1000;

hundred=(int)(num-ten_thousand*10000-thousand*1000)/100;

ten=(int)(num-ten_thousand*10000-thousand*1000-hundred*100)/10;

indiv=(int)(num-ten_thousand*10000-thousand*1000-hundred*100-ten*10); cout<<\ switch(place) {case

5:cout<

case 4:cout<

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4