c++书中例题源代码第4章.docVIP

  • 7
  • 0
  • 约6.72千字
  • 约 10页
  • 2017-05-12 发布于河南
  • 举报
c书中例题源代码第4章

【例4.1】 从键盘上输入两个浮点数,编程比较大小,输出显示相等、大于、小于等情况。 #include iostream.h void main( ) { double x,y; coutInput x,y: ; cinxy; if(x!=y) if(xy) coutxy\n; else coutxy\n; else coutx=y\n; } 【例4.2】 分析下列程序的输出结果,指出该程序中的else子句与哪个if配对。 #include iostream.h void main( ) { int i(7),j(5); if(i!=j) if(i==j) { i+=8; coutiendl; } else { j-=2; coutjendl; } couti+jendl; } 【例4.3】 分析下列程序的输出结果,并且指出该程序中的else子句与哪个if配对。 #include iostream.h void main( ) { int i(7),j(5); if(i!=j) { if(i=j) { i+=8; coutiendl; } } else { j-=2; coutjendl; } couti+jendl; } 【例4.4】 编程实现两个浮点数的四则运算。 #include iostream.h void main( ) { double d1,d2; char op; coutInput d1 op d2: ; cind1opd2; switch(op) { double temp; case +: temp=d1+d2; coutd1opd2=tempendl; break; case -: temp=d1-d2; coutd1opd2=tempendl; break; case *: temp=d1*d2; coutd1opd2=tempendl; break; case /: temp=d1/d2; coutd1opd2=tempendl; break; default: couterror!\n; } } 【例4.5】 编程统计从键盘上输入的每种数字字符的个数和其他字符的个数,并以字符 # 作为输入结束符。 #include iostream.h void main( ) { char ch; int nother(0),ndigit[10]; for(int i=0;i10;i++) ndigit[i]=0; coutInput some characters:\n; cinch; while(ch!=#) { switch(ch) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: ++ndigit[ch-0]; break; default: ++nother; } cinch; } coutdigit=; for(i=0;i10;i++) coutndigit[i] ; cout\nother=notherendl; } 【例4.6】 分析下列程序的输出结果,该程序中出现了开关语句的嵌套使用。 #include iostream.h void main( ) { int a(1),b(6),c(4),d(2); switch(a++) { case 1: c++;d++; case 2: switch(++b) { case 7: c++; case 8: d++; } case 3: c++;d++; break; case 4: c++; d++; } coutc,dendl; } 【例4.7】 编程求出自然数51~100之和。 #include iostream.h void main( ) { int i(51),sum(0); while(i=100) { sum+=i; i++; } coutsum=su

文档评论(0)

1亿VIP精品文档

相关文档