C典型案例及常见错误分析_第1页
C典型案例及常见错误分析_第2页
C典型案例及常见错误分析_第3页
C典型案例及常见错误分析_第4页
C典型案例及常见错误分析_第5页
已阅读5页,还剩59页未读 继续免费阅读

下载本文档

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

文档简介

1、C+简单程序典型案例【案例2-1】设计一个编写仅包含C+程序基本构成元素的程序/*      /注释行开始This is the first C+ program.       Designed by zrf */     /注释行结束#include <iostream>    /包含头文件using namespace std;    /打开命名空间std/ This is the

2、 main function /单行注释语句int main(void)    /主函数,程序入口    /块作用域开始 int age;     /声明一个变量   age= 20;       /赋值语句   cout<<"The age is:n"   /输出一个字符串   cout<

3、<age<<endl;      /输出变量中的值 return 0;     /主函数返回0    /块作用域结束        【案例2-2】计算圆的周长和面积C+语言中常量、变量#include <iostream>using namespace std;int main() const float PI=3.1415926;  /

4、float 型常量 float r=2.0;    /用float 型常量初始化变量 cout<<"r="<<r<<endl;  /输出圆的半径 float length;    /float型变量声明 length=2*PI*r;    /计算圆的周长 cout<<"Length="<<length<<endl; 

5、/输出圆的周长 float area=PI*r*r;   /计算圆的面积 cout<<"Area="<<area<<endl; /输出圆的面积 return 0; 【案例2-3】整数的简单运算除法、求余运算法和增量减量运算符#include <iostream> using namespace std; int main()  int x, y;  x = 10;  y = 3;  cout << x &l

6、t;< " / " << y << " is " << x / y    /整数的除法操作    <<" with x % y is " << x % y << endl;     /整数的取余操作 x +;   -y ;      /使用增量减量运算符 cou

7、t << x << " / " << y << " is " << x / y << "n"     /整数的除法操作    << x << " % " << y << " is " << x % y<<endl;  /整数的取余操作 return 0;  

8、;【案例2-4】多重计数器前置和后置自增运算符#include<iostream>  using namespace std; int main()    int iCount=1; iCount=(iCount+)+(iCount+)+(iCount+); /后置+ cout<<"The first  iCount="<<iCount<<endl; iCount=1; iCount=(+iCoun

9、t)+(+iCount)+(+iCount); /前置+ cout<<"The second iCount="<<iCount<<endl; iCount=1; iCount=-iCount+;    /后置+ cout<<"The third  iCount="<<iCount<<endl; iCount=1; iCount=-+iCount; 

10、0;  /前置+ cout<<"The fourth  iCount="<<iCount<<endl; return 0;  【案例2-5】对整数“10”和“20”进行位运算位运算的应用#include <iostream>using namespace std;int main()        cout << "20&10=" << (20&a

11、mp;10) << endl;  /按位与运算    cout << "2010=" << (2010) << endl;  /按位异或运算    cout << "20|10=" << (20|10) << endl;  /按位或运算    cout << "20=" <<(20

12、) << endl;          /按位取反运算    cout << "20<<3=" << (20<<3) << endl;  /左移位运算    cout << "-20<<3=" << (-20<<3) << endl;  

13、/左移位运算    cout << "20>>3=" << (20>>3) << endl;  /右移位运算    cout << "-20>>3=" << (-20>>3) << endl;  /右移位运算 return 0; 【案例2-6】实现逻辑“异或”运算逻辑运算应用#include <iostream&

14、gt; using namespace std; int main()  bool p, q;  p = true;   q = true;  cout <<p <<" XOR "<<q<<" is "<<( (p | q) && !(p && q) )<< "n" /输出异或结果 p = false;   q = true;  cout &l

15、t;<p<<" XOR "<<q<< " is "<<( (p | q) && !(p && q) )<< "n" /输出异或结果 p = true;   q = false;  cout <<p<<" XOR "<<q<<" is "<<( (p | q) && !(p &&

16、amp; q) )<< "n" /输出异或结果 p = false;   q = false;  cout <<p<<" XOR "<<q<<" is "<<( (p | q) && !(p && q) )<< "n" /输出异或结果 return 0;  【案例2-7】高效筛选器用条件运算符“?”构建条件表达式#include<ios

17、tream>using namespace std;int main()  int iNum1=1,iNum2,iMax; cout<<"Please input two integers:n"    cin>>iNum1>>iNum2; iMax = iNum1>iNum2 ? iNum1 : iNum2;  /使用条件运算符构建条件表达式 cout<<"The max integer is: "<

18、<iMax<<endl;   return 0; 【案例2-8】“多计算与单提取”功能的实现逗号表达式#include<iostream>using namespace std;int main()    int Val1, Val2, Val3, Left, Midd, Righ; Left = 10; Midd = 20;   Righ = 30;   Val1 = (Left+, -Midd, Righ+);   /使用

19、逗号表达式 Val2 = (Righ+, Left+, -Midd);  /使用逗号表达式 Val3 = ( -Midd, Righ+,Left+);  /使用逗号表达式    cout <<"Val1=t"<<Val1 <<"nVal2=t"<<Val2 <<"nVal3=t"<<Val3<<endl;    return 0; 【案例2-9

20、】高效的算术运算符复合赋值运算符#include <iostream>using namespace std;int main() int n=20;  cout << "n = " << n << endl; n += 8;   cout << "After n += 8, n = " << n << endl;  /使用复合的赋值运算符+= n -= 6;   cout <

21、< "After n -= 6, n = " << n << endl;  /使用复合的赋值运算符-= n *= 1;   cout << "After n *= 1, n = " << n << endl; /使用复合的赋值运算符*= n /= 4;   cout << "After n /= 4, n = " << n << endl;  /

22、使用复合的赋值运算符/= n %= 3;  cout << "After n %= 3, n = " << n << endl;  /使用复合的赋值运算符%= return 0; 【案例2-10】计算不同数据类型的存储容量sizeof运算符#include <iostream>using namespace std ;int main() cout << "The size of an int is:tt" << sizeo

23、f(int) << " bytes.n" cout << "The size of a short int is:t" << sizeof(short) << " bytes.n" cout << "The size of a long int is:t" << sizeof(long) << " bytes.n" cout << "The size of a

24、char is:tt" << sizeof(char) << " bytes.n" cout << "The size of a wchar_t is:t" << sizeof(wchar_t) << " bytes.n" cout << "The size of a float is:tt" << sizeof(float) << " bytes.n" cou

25、t << "The size of a double is:t" << sizeof(double) << " bytes.n" return 0; 【案例2-11】巧妙获取整数部分double和int数据类型的转换#include <iostream>using namespace std;int main()   int nn=10,mm;    double xx=4.741,yy;     cout&

26、lt;<"nn*xx="<<nn*xx<<endl;     /表达式类型转换    mm=xx;    yy=nn;         /赋值类型转换    cout<<"mm="<<mm<<endl <<"yy="<<yy<<

27、endl;    cout<<"int(xx)="<<int(xx)<<endl <<"(int)xx="<<(int)xx<<endl;    /强制类型转换    cout<<"int(1.412+xx)="<<int(1.412+xx)<<endl;      /强制类型转换 

28、0;  cout<<"(int)1.412+xx="<<(int)1.412+xx<<endl;     /强制类型转换 return 0; 【案例2-12】将分数转换为小数强制类型转换#include <iostream> using namespace std; int main() for( int i=1; i <= 5; +i )   cout << i << "/ 3 is:

29、" << (float) i / 3 << endl;     /强制类型转换 return 0;  【案例2-13】安全的除法计算器#include <iostream> using namespace std; int main()  int a, b;  cout << "Enter numerator: "    cin >> a;  cout << "En

30、ter denominator: "    cin >> b;  if(b) cout << "Divide Result is: " << a / b << 'n'  /排除除数为零的情况 else cout << "Divide by zero!n"  return 0;  【案例2-14】猜数游戏嵌套的if条件语句#include <iostream> #include &

31、lt;cstdlib> using namespace std; int main()  int MagNum, GueNum;   MagNum = rand();      /产生随机数 cout << "Enter the Guess number: "   cin >> GueNum;  if (GueNum = MagNum)         &#

32、160;/if语句块起始位置  cout << "* It is Right *n"<< MagNum << " is the Magess number.n"         /if语句块结束位置 else          / else语句块起始位置  cout << "Sorry, y

33、ou're wrong."<<endl;   if(GueNum > MagNum)       cout <<"Guessed number is too high.n"   else      cout << "Guessed number is too low.n"        &

34、#160; /else语句块结束位置 return 0;  【案例2-15】根据输入月份输出从年初到本月底的天数不带break的switch#include <iostream>using namespace std;int main() int year,month,days=0; cout<<"Input year and month:"  cin>>year>>month; switch (month)     

35、  /每个case分支均没有break语句   case 12: days +=31;  case 11: days +=30;   case 10: days +=31;  case  9: days +=30;  case  8: days +=31;  case  7: days +=31;  case  6: days +=30;  case  5: days

36、 +=31;  case  4: days +=30;  case  3: days +=31;   case  2:      /判断是否为闰年   if (year % 4=0 && year % 100!=0 | year %400=0)           days +=29;  &#

37、160;else           days +=28;  case  1: days +=31;  if (days=0)    cout<< "Wrong month"<<endl; else     cout << "Total days is:" <<days<&l

38、t; endl; return 0; 【案例2-16】计算数的阶乘do-while循环语句#include <iostream>using namespace std;int main()  long limits;   cout << "Enter a positive integer: "   cin >> limits;   cout << "Factorial numbers of "<<0<

39、<" is " << 1<<endl;   cout << "Factorial numbers of "<<1<<" is " << 1<<endl;   long fac=1, i=1;   do       /使用do-while循环   fac *= +i;   

40、;    cout << "Factorial numbers of "<<i<<" is " << fac<<endl;  while (fac < limits);   return 0; 【案例2-17】计算数的阶乘for循环#include <iostream>using namespace std;int main()  long limits;   cout <<

41、"Enter a positive integer: "   cin >> limits;   cout << "Factorial numbers of "<<0<<" is " << 1<<endl;   cout << "Factorial numbers of "<<1<<" is " << 1<<

42、endl;   long fac=1; for(int i=2;fac<=limits;i+)    /使用for 循环   fac *= i;    cout << "Factorial numbers of "<<i<<" is " << fac<<endl;  return 0; 【案例2-18】筛选素数步长为2的for循环#inclu

43、de <iostream>#include <cstdlib>using namespace std;int main() long n; cout << "Enter a positive integer: "  cin >> n; if (n < 2)      cout << n << " is not prime." << endl; else if (n &

44、lt; 4)      cout << n << " is prime." << endl; else if (n%2 = 0)      cout << n << " = 2*" << n/2 << endl; else  for (int i=3; i <= n/2; i += 2)  /步长为2

45、0;   if (n%i = 0)          cout << n << " = " << i << "*" << n/i << endl;  exit(0);   cout << n << " is prime." << endl;  return 0; 【案例2

46、-19】输出120之间的偶数continue语句#include <iostream> using namespace std; int main()  cout<<"The even numbers are as follows:"<<endl;  for(int i=0; i<=20; i+)   if(i%2) continue;  /根据条件使用continue结束本次循环  cout << i << ' ' 

47、60;  return 0;  【案例2-20】统计输入整数的个数并求和exit()函数#include <iostream> #include <cstdlib>using namespace std; int main()  int sum=0,num=0,m;  cout<<"Please input integers (0:end):"<<endl;  do cin>>m;   num+;   sum+=m; 

48、;    if(m=0)     cout<<"Entered numbers:"<<num<<" integers.n"   cout<<"The sum is:"<<sum<<endl;   exit(0); / 使用exit()函数终止程序      while(1);&

49、#160;return 0;  【案例2-21】“剪刀、石头、布”游戏枚举类型#include <iostream>using namespace std;enum Choice ROCK, CLOTH, SCISS; /声明枚举类型Choiceenum Winner Play1, Play2, Tie;   /声明枚举类型Winnerint main() int n;    Choice cho1, cho2;     Winner winner; c

50、out << "Choose rock (0), cloth (1), or Sciss (2):" << endl; cout << "Player No. 1: " cin >> n; cho1 = Choice(n); cout << "Player No. 2: " cin >> n; cho2 = Choice(n); if (cho1 = cho2) winner = Tie;

51、60;else if (cho1 = ROCK)  if (cho2 = CLOTH)  winner = Play2;  else  winner = Play1; else if (cho1 = CLOTH)  if (cho2 = SCISS)  winner = Play2;  else  winner = Play1; else   if (cho2 = ROCK)  winner = Play2; 

52、60;else  winner = Play1; if (winner = Tie)   cout << "tTied!n" else if (winner = Play1)  cout << "tPlayer No. 1 wins." <<endl; else  cout << "tPlayer No. 2 wins." << endl; return 0; 【案例2-22】

53、简单的学生信息类型结构体#include <iostream>#include <iomanip>using namespace std;struct student             /学生信息结构体   int num;    char name20;    char gender;    int age; stu1=1001,"Zh

54、ang San",'M',19;int main() student stu2=1002,"Li Si",'M',20;  /声明结构体变量并初始化 student stu3=1003,"Wang Hong",'F',22;         /声明结构体变量并初始化    cout<<setw(7)<<stu1.num<

55、<setw(20)<<<<setw(3)<<stu1.gender<<setw(3)<<stu1.age<<endl; cout<<setw(7)<<stu2.num<<setw(20)<<<<setw(3)<<stu2.gender<<setw(3)<<stu2.age<<endl; cout<<setw(7)<<stu3.num

56、<<setw(20)<<<<setw(3)<<stu3.gender<<setw(3)<<stu3.age<<endl; return 0; 【案例2-23】综合案例百钱买百鸡问题#include<iostream>using namespace std;int main()       int n=100;   cout<<"鸡公  鸡母  鸡雏"&

57、lt;<endl;      /i表示鸡公,j表示鸡母,k表示鸡雏   for ( int i = 1; i <= n; i+ )   for ( int j = 1; j <= n; j+ )    for( int k = 1; k <= n; k+ )     if( n = 5 * i + 3 * j + k / 3 ) && ( k % 3 = 0 ) && ( n =

58、i + j + k )       cout << i << "  " << j << "  " << k << endl;   return 0;#include<stdio.h>int main()   int x,y,z,j=0;   printf("Folleing are possible plans to buy

59、 100 fowls with 100 Yuan.n");   for(x=0;x<=20;x+)         /外层循环控制鸡翁数      for(y=0;y<=33;y+)      /内层循环控制鸡母数y在033变化             &#

60、160; z=100-x-y;           /内外层循环控制下,鸡雏数z的值受x,y的值的制约         if(z%3=0&&5*x+3*y+z/3=100)        /验证取z值的合理性及得到一组解的合理性         

61、;      printf("%2d:cock=%2d hen=%2d chicken=%2dn",+j,x,y,z);      【案例3-1】编写输出专用函数无参函数#include<iostream>using namespace std;void DispMessage(void)               

62、;     /定义无参函数    cout<<"This is a Message!"<<endl;       int main()     DispMessage();                  

63、0;         /调用无参函数DispMessage    return 0; 【案例3-2】编写求和函数有参函数#include<iostream>using namespace std;double add(double x,double y)                    /定义有参函数

64、    double z;    z=x+y;    return(z); int main()       double a=0.5, b=1.0;    cout<<"add(a,b)="<<add(a,b)<<endl;   /调用有参函数add()    return 0; 【案例3-3】编写求和函数函数的不同调用

65、形式#include<iostream>using namespace std;double add(double x,double y)                    /函数的定义,其有返回值       double z;    z=x+y;    cout<<x<&

66、lt;"+"<<y<<"="<<z<<endl;    return(z);int main()    double a=0.5,b=1.0;/以不同参数形式调用函数add()    cout<<"add(1.5,2.5)="<<add(1.5,2.5)<<endl;    cout<<"add(a,b)=&qu

67、ot;<<add(a,b)<<endl;    cout<<"add(2*a,a+b)="<<add(2*a,a+b)<<endl;    double c=2*add(a,b);                       &#

68、160;             /以表达式方式调用函数add()    cout<<"c="<<c<<endl;    add(2*a,b);                   &

69、#160;                                 /以语句方式调用函数add()    cout<<" add(a, add(a,b)="<<add(a, add(a,b)<<e

70、ndl;       /以函数参数形式调用函数add()    return 0; 【案例3-4】编写符号函数函数的返回值#include<iostream>using namespace std;int sgn(double x)                      &

71、#160;/定义符号函数sgn(),其返回值为int类型       if (x>0) return(1);                  /返回出口1    if (x<0) return(-1);            

72、    /返回出口2    return(0);                             /返回出口3int main()       double x;    &

73、#160; for (int i=0;i<=2;i+)            cout<<"Input x="     cin>>x;       cout<<"sgn("<<x<<")="<<sgn(x)<<endl;    &

74、#160;   return 0; 【案例3-5】编写最值函数函数原型声明#include<iostream>using namespace std;/函数原型声明语句也可以在这里int main()         float max(float,float);                   

75、60;        /max()函数原型声明语句    float a,b,Max;                                  

76、60;   /变量声明语句    cout<<" Input a="    cin>>a;              /输入参数a    cout<<" Input b="    cin>>b;   &

77、#160;         /输入参数b    Max=max(a,b);                                 /调用max()函数 

78、0;   cout<<"max("<<a<<","<<b<<")="<<Max<<endl;    return 0;float max(float x,float y)     float z;    z=(x>y)?x:y;        return(z); &#

79、160;                                         /返回值类型为浮点型  【案例3-6】值传递和引用传递的区别#include <iostream>

80、 using namespace std;void fun(int,int&);                             /函数参数一个为值传递,一个引用传递int main()     int a = 22, b = 44;    cout &

81、lt;< "Initial a = " << a << ", b = " << b << endl;    fun(a,b);    cout << "After fun(a,b), a = " << a << ", b = " << b << endl;    fun(2*a-3,b);   

82、cout << "After fun(2*a-3,b), a = " << a << ", b = " << b << endl;    return 0;void fun(int x, int& y)     x = 88;  y = 99; 【案例3-7】编写最值函数内联函数#include<iostream>using namespace std;inline int max(int x,i

83、nt y)                  /使用inline关键字声明max()为内联函数    return x>y?x:y; int main()        int a=3,b=5,c;    c=max(a,b);    cout<<"max("&

84、lt;<a<<","<<b<<")="<<c<<endl;    cout<<"max("<<15<<","<<11<<")="<<max(15,11)<<endl;    return 0;        &

85、#160;           /计算面积和周长 【案例3-9】最小公倍数函数函数的嵌套调用#include <iostream>  using namespace std;long int gcd(long int m,long int n)                  

86、0;           /求最大公约数     if (m < n) swap(m,n); while (n>0)                    int r = m%n; m = n;   n = r;  &

87、#160;           return m;long int lcm(long int m,long int n)                            /求最小公倍数    return

88、 m*n/gcd(m,n); int main()     int m, n;    cout << "Please input two integers: " cin >> m >> n;    cout << "lcm(" << m << "," << n << ") = " << lcm(m,n

89、) << endl;    return 0; 【案例3-10】显示函数的参数带默认参数的函数#include <iostream>using namespace std;void disp(int x=1,int y=1,int z=1)                         /带有默认参数值

90、的函数       cout<<"Parameter 1 is: "<<x<<endl;    cout<<"Parameter 2 is: "<<y<<endl;    cout<<"Parameter 3 is: "<<z<<endl;int main()      

91、                                 /main()函数中测试参数带有默认值的函数disp()     cout<<"No actual parameter"<<endl;

92、60;   disp();    cout<<"One actual parameter"<<endl;    disp(1);    cout<<"Two actual parameter"<<endl;    disp(1,2);    cout<<"Three actual parameter"<

93、<endl;    disp(1,2,3);    return 0; 【案例3-11】通用最值函数参数数目可变的函数#include <iostream>#include <cstdarg>using namespace std;int max(int,int.);                   &#

94、160;            /原型声明int main()      int a,b,c,d,e;    cout<<"Enter five integers, seperate with space:" cin>>a>>b>>c>>d>>e;    cout<<"The

95、 maxmum in a and b is:"<<max(2,a,b)<<endl;    cout<<"The maxmum in five integers is:"<<max(5,a,b,c,d,e)<<endl;    return 0;int max(int num,int integer.)             

96、/定义参数数目可变的函数     va_list ap;     int n=integer;    va_start(ap,integer);    for(int i=1;i<num;i+)     int t=va_arg(ap,int); if(t>n)            n=t;&#

97、160;       va_end(ap);    return n;【案例3-12】多变的最值函数参数数目不同的重载函数#include <iostream>using namespace std;int main()     int min (int a, int b, int c);               

98、;         /函数声明    int min (int a, int b);                                /函数声明    in

99、t i1 ,i2,i3,i;    cout<<"Enter three integers:" cin >>i1 >>i2 >>i3;                    /输入3个整数    i = min(i1 ,i2) ;  cout <<"

100、The min in two intergers=" <<i <<endl;     / 2个整数中最小者    i = min(i1 ,i2 ,i3) ;                            &#

101、160;    / 3个整数中最小者    cout <<"The min in three intergers=" <<i <<endl;    return 0;int min(int a,int b,int c)                    

102、60;        /定义求3个整数中的最小者的函数     int k;      k=(a<b)?a:b;    k=(k<c)?k:c;    return k;int min(int a,int b)              

103、                      /定义求2个整数中的最小者的函数     int k;    k=(a<b)?a:b;    return k; 【案例3-13】求绝对值使用系统函数#include <iostream>#include <cmath&g

104、t;#include <cstdlib>using namespace std;void main( void )     int     ix = -4, iy;    long    lx = -41567L, ly;    double  dx = -3.141593, dy;    iy = abs( ix );   cout<<&qu

105、ot;The absolute value of"<<ix <<" is "<<iy<<endl;    ly = labs( lx );   cout<<"The absolute value of"<<lx <<" is "<<ly<<endl;    dy = fabs( dx );   cout<<&

106、quot;The absolute value of"<<dx <<" is "<<dy<<endl; 【案例3-14】将整数和小数分离使用系统函数#include<iostream>#include<cmath>using namespace std;void main(void)     double fraction, integer,number = 103.567;    fraction = modf(

107、number, &integer);    cout<<number<<"整数部分为:"<<integer<<" 小数部分为:"<<fraction; 【案例3-15】求平方根使用系统函数#include <iostream>#include <cmath>#include <cstdlib>using namespace std;void main( void )    

108、 double question = 45.35, answer;    answer = sqrt( question );    if( question < 0 )       cout<<"Error: sqrt returns "<<answer<<endl;    else       cout<<&q

109、uot;The square root of "<<question<<" is "<<answer<<endl; 【案例3-16】求随机数使用系统函数#include <iostream>#include <cstdlib>#include <ctime>using namespace std;void main(void)     cout << "RAND_MAX=" << RAND_MAX << endl;    cout<<"产生10个 0 到 99的随机数如下:n&q

温馨提示

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

评论

0/150

提交评论