c++的头文件和经典程序代码大全
C程序代码大全

//根据半径计算圆的周长和面积#include <iostream.h>const float PI=3.1416; //声明常量(只读变量)PI为3.1416float fCir_L(float); //声明自定义函数fCir_L()的原型float fCir_S(float); //声明自定义函数fCir_S()的原型//以下是main()函数main(){float r,l,s; //声明3个变量cout<<"r="; //显示字符串cin>>r; //键盘输入l=fCir_L(r); //计算圆的周长,赋值给变量ls=fCir_S(r); //计算圆的面积,赋值给变量scout<<"l="<<l; //显示计算结果cout<<"\ns="<<s;}//定义计算圆的周长的函数fCir_L()float fCir_L(float x){float z=-1.0; //声明局部变量if (x>=0.0) //如果参数大于0,则计算圆的周长z=2*PI*x;return(z); //返回函数值}//定义计算圆的面积的函数fCir_S()float fCir_S(float x){float z=-1.0; //声明局部变量if (x>=0.0) //如果参数大于0,则计算圆的面积z=PI*x*x;return(z); //返回函数值}/* Program: P1-2.CPPWritten by: HapDate written: 02:11:10*/#include <iostream.h>void main(void){double s1,s2,s3;s1=1.5; /* 对变量s1赋值*/cout<<"s1="<<s1<<endl;/* 对变量s2赋值*/ s2=2.5;cout<<"s2="<<s2<<endl;s3= /* 对变量s3赋值*/ 3.5;cout<<"s3="<<s3<<endl;cout<<"s1+s2+s3="<<s1+s2+s3<<endl; //计算并显示//计算并显示 cout<<"s1+s2+s3="<<s1+s2+s3<<endl;}#include <iostream.h>main(){double r=1.0;cout<<"r="<<r<<endl;double l;l=2*3.1416*r; //计算圆的周长,赋值给变量l cout<<"l="<<l<<endl; //显示圆的周长double s=3.1416*r*r; //计算圆的面积,赋值给变量s cout<<"s="<<s<<endl; //显示圆的面积cout<<"r="; //显示提示输入的信息cin>>r; //键盘输入l=2*3.1416*r; //计算圆的周长,赋值给变量l cout<<"l="<<l<<endl; //显示圆的周长s=3.1416*r*r;cout<<"s="<<s<<endl; //显示圆的面积}#include <iostream.h> //包含iostream.h头文件void main(){//输出字符常量、变量和字符串char c1='A';cout<<'W';cout<<c1<<endl;cout<<"This is a test."<<endl;cout<<"------------------"<<endl;//输出整型常量、变量和表达式int n=100;cout<<10;cout<<n;cout<<2*n<<endl; //输出整型表达式cout<<"------------------"<<endl;//输出浮点型常量、变量和表达式double pi=3.1415926,r=10.0,s=pi*r*r;cout<<pi<<endl;cout<<r;cout<<s;cout<<2*r*pi<<endl; //输出浮点型表达式cout<<"------------------"<<endl;//一个cout可以输出多项数据cout<<'W'<<" "<<c1<<endl;cout<<"This is a test."<<endl;cout<<"pi="<<pi<<" r="<<r<<" s="<<s<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//输入输出字符char c;cin>>c;cout<<"c="<<c<<endl;//输入输出整型数据int n;cin>>n;cout<<"n="<<n<<endl;//输入输出浮点型数据double x;cin>>x;cout<<"x="<<x<<endl;//输入提示cout<<"n=";cin>>n;cout<<"n="<<n<<endl;//多项输入cout<<"c n x"<<endl;cin>>c>>n>>x;cout<<"c="<<c<<" n="<<n<<" x="<<x<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//声明整型变量int a,b;//从键盘上为整型变量赋值cout<<"a=";cin>>a;cout<<"b=";cin>>b;//整型数的算术运算cout<<a<<"+"<<b<<"="<<a+b<<endl;cout<<a<<"-"<<b<<"="<<a-b<<endl;cout<<a<<"*"<<b<<"="<<a*b<<endl;cout<<a<<"/"<<b<<"="<<a/b<<endl;cout<<a<<"%"<<b<<"="<<a%b<<endl;//测试溢出short n=32767,m; //n取short类型的最大值 cout<<"n="<<n<<endl;m=n+1; //引起溢出cout<<"n+1="<<m<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//声明变量,并初始化int a=010,b=10,c=0X10;//以十进制形式显示数据cout<<"DEC:";cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以八进制形式显示数据cout<<"OCT:";cout<<oct; //指定八进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以十六进制形式显示数据cout<<"HEX:";cout<<hex; //指定十六进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//八、十和十六进制数混合运算并输出cout<<"a+b+c=";cout<<dec; //恢复十进制输出cout<<a+b+c<<endl;//测试八、十和十六进制输入cout<<"DEC:a="; cin>>a;cout<<"OCT:b="; cin>>b;cout<<"HEX:a="; cin>>c;cout<<"DEC:"<<dec<<endl; //指定十进制输出cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;cout<<"c="<<c<<endl;}#include <iostream.h> //包含iostream.h头文件#include<iomanip.h> // iomanip.h头文件包含setprecision()的定义main(){//float型变量的声明、输入、计算和输出float fx,fy;cout<<"fx=";cin>>fx;cout<<"fy=";cin>>fy;cout<<fx<<"+"<<fy<<"="<<fx+fy<<endl;cout<<fx<<"-"<<fy<<"="<<fx-fy<<endl;cout<<fx<<"*"<<fy<<"="<<fx*fy<<endl;cout<<fx<<"/"<<fy<<"="<<fx/fy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!//double型变量的声明、输入、计算和输出float dx,dy;cout<<"dx=";cin>>dx;cout<<"dy=";cin>>dy;cout<<dx<<"+"<<dy<<"="<<dx+dy<<endl;cout<<dx<<"-"<<dy<<"="<<dx-dy<<endl;cout<<dx<<"*"<<dy<<"="<<dx*dy<<endl;cout<<dx<<"/"<<dy<<"="<<dx/dy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!//测试float和double类型数据的有效位fx=10.0;fy=6.0;float fz=fx/fy;dx=10.0;dy=6.0;double dz=dx/dy;cout<<"fz=";cout<<setprecision(20)<<fx<<"/"<<fy<<"="<<fz<<endl;cout<<"dz=";cout<<setprecision(20)<<dx<<"/"<<dy<<"="<<dz<<endl<<endl;; //float型溢出float x=3.5e14;cout<<"x="<<x<<endl;cout<<"x*x="<<x*x<<endl;cout<<"x*x*x="<<x*x*x<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//字符类型变量的声明char c1='A';char c2;//字符数据的运算及输出c2=c1+32;cout<<"c1="<<c1<<endl;cout<<"c2="<<c2<<endl;//输出字符及ASCII码cout<<c1<<" : "<<int(c1)<<endl;cout<<c2<<" : "<<int(c2)<<endl;cout<<'$'<<" : "<<int('$')<<endl;//输入字符cout<<"c1 c2"<<endl;cin>>c1>>c2;cout<<"c1="<<c1<<" c2="<<c2<<endl;}#include <iostream.h> //包含iostream.h头文件main(){char c1='\a',TAB='\t';//阵铃一声cout<<c1<<endl;//使用水平制表符cout<<1<<TAB<<2<<TAB<<3<<TAB<<4<<endl;//使用双引号cout<<"He said \"Thank you\"."<<endl; //使用回车换行cout<<"abc\n"<<"def"<<'\n';}#include <iostream.h> //包含iostream.h头文件main(){//声明bool变量,并初始化bool flag1=false,flag2=true;//输出布尔常量和变量cout<<"false:"<<false<<endl;cout<<"true: "<<true<<endl;cout<<"flag1="<<flag1<<endl;cout<<"flag2="<<flag2<<endl;//布尔变量的赋值和输出int x=1;flag1=x>0; //存放关系运算结果cout<<"flag1="<<flag1<<endl;flag2=flag1; //bool类型变量相互赋值cout<<"flag2="<<flag2<<endl;//布尔变量超界处理flag1=100;cout<<"flag1="<<flag1<<endl;flag2=-100;cout<<"flag2="<<flag2<<endl;}#include <iostream.h>const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){//声明3个变量double r,l,s;//输入圆的半径cout<<"r=";cin>>r;//计算圆的周长l=2*PI*r;cout<<"l="<<l<<endl;//计算圆的面积s=PI*r*r;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//定义枚举类型,并指定其枚举元素的值enum color {RED=3,YELLOW=6,BLUE=9};//声明枚举变量a和b,并为枚举变量a赋初值enum color a=RED;color b; //合法,与C语言不同// 输出枚举常量cout<<"RED="<<RED<<endl;cout<<"YELLOW="<<YELLOW<<endl;cout<<"BLUE="<<BLUE<<endl;//枚举变量的赋值和输出b=a;a=BLUE;cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;//a=100; 错误!//a=6 也错误!//枚举变量的关系运算b=BLUE; // 枚举变量的赋值运算cout<<"a<b="<<(a<b)<<endl;}#include <iostream.h>const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){//声明3个变量double r=3,l,s;//计算圆的周长l=2*PI*r;cout<<"l="<<l<<endl;//计算圆的面积s=PI*r*r;cout<<"s="<<s<<endl;//验证赋值误差int il,is;il=l;is=s;cout<<"il="<<il<<endl;cout<<"is="<<is<<endl;}#include <iostream.h>main(){//变量声明char c;double x,y;//测试自增cout<<"++E and E++ :"<<endl;c='B';cout<<"c="<<++c<<endl; //输出c=Cc='B';cout<<"c="<<c++<<endl; //输出c=Bx=1.5;y=5+ ++x; //加号后的空格不能少cout<<"y="<<y<<endl; //输出y=7.5x=1.5;y=5+x++;cout<<"y="<<y<<endl; //输出y=6.5cout<<"--------------------"<<endl;//测试自减cout<<"--E and E-- :"<<endl;c='B';cout<<"c="<<--c<<endl; //输出c=Ac='B';cout<<"c="<<c--<<endl; //输出c=Bx=1.5;y=5+--x;cout<<"y="<<y<<endl; //输出y=5.5x=1.5;y=5+x--;cout<<"y="<<y<<endl; //输出y=6.5}#include <iostream.h>main(){int a=3, b=2;//输出关系表达式cout<<a<b<<endl;cout<<(a<b)<<(a>b)<<(a>=b)<<(a==b)<<(a!=b)<<endl;bool flag=2*a<b+10;cout<<"flag="<<flag;}#include <iostream.h>main(){float a=3.5,b=2.1,c=0;cout<<"a="<<a<<" b="<<b<<" c="<<c<<endl;//与运算cout<<"a&&b="<<(a&&b)<<endl;//输出1cout<<"a&&c="<<(a&&c)<<endl;//输出0//或运算cout<<"a||b="<<(a||b)<<endl;//输出1cout<<"a||c="<<(a||c)<<endl;//输出1//非运算cout<<"!a="<<!a<<endl<<"!c="<<!c<<endl;//输出0 1//关系运算和逻辑运算bool flag=a>=0 && a<=5; //变量a在[0,5]区间内cout<<"a=>0 && a<=5="<<flag<<endl;//输出1//算术运算、关系运算和逻辑运算cout<<"a+5>2*b+2||a<b+3="<<(a+5>2*b+2||a<b+3)<<endl;//输出1 }#include <iostream.h>main(){//按位与运算cout<<"24&12="<<(24&12)<<endl;//按位异或运算cout<<"24^12="<<(24^12)<<endl;//按位或运算cout<<"24|12="<<(24|12)<<endl;//按位取反运算cout<<"~24="<<(~24)<<endl;//左移位运算cout<<"5<<3="<<(5<<3)<<endl;cout<<"-5<<3="<<(-5<<3)<<endl;//右移位运算cout<<"5>>3="<<(5>>3)<<endl;cout<<"-5>>3="<<(-5>>3)<<endl;}#include <iostream.h>main(){int a=1,b=1,c=3;//显示a,b,c的值cout<<"a="<<a<<" b="<<b<<" c="<<c<<endl;//计算显示(1) b+=a+2*c%5; 的结果b+=a+2*c%5; //相当于表达式语句 b=b+(a+2*c%5);cout<<"(1) b="<<b<<endl;//计算显示(2) a<<=c-2*b; 的结果a=1,b=1,c=3;a<<=c-2*b; // 相当于表达式语句 a=a<<(c-2*b);cout<<"(2) a="<<a<<endl;//计算显示(3) a*=b=c=3;的结果a=1,b=1,c=3;a*=b=c=3; //相当于语句组 c=3;b=c;a=a*b;cout<<"(3) a="<<a<<" b="<<b<<" c="<<c<<endl;//计算显示(4) a+=b+=c;的结果a=1,b=1,c=3;a+=b+=c; //相当于语句组 b=b+c; a=a+b;cout<<"(4) a="<<a<<" b="<<b<<" c="<<c<<endl;//计算显示(5) a-=b=++c+2;的结果a=1,b=1,c=3;a-=b=++c+2; //相当于语句组 ++c;b=b+c+2;a=a-b; cout<<"(5) a="<<a<<" b="<<b<<" c="<<c<<endl;}#include <iostream.h>main(){//用 sizeof 计算各类种常量的字节长度cout<<"sizeof('$')="<<sizeof('$')<<endl;cout<<"sizeof(1)="<<sizeof(1)<<endl;cout<<"sizeof(1.5)="<<sizeof(1.5)<<endl;cout<<"sizeof(\"Good!\")="<<sizeof("Good!")<<endl;//用sizeof 计算各类型变量的字节长度int i=100;char c='A';float x=3.1416;double p=0.1;cout<<"sizeof(i)="<<sizeof(i)<<endl;cout<<"sizeof(c)="<<sizeof(c)<<endl;cout<<"sizeof(x)="<<sizeof(x)<<endl;cout<<"sizeof(p)="<<sizeof(p)<<endl;//用sizeof 计算表达式的字节长度cout<<"sizeof(x+1.732)="<<sizeof(x+1.732)<<endl;//用 sizeof 计算各类型的字节长度cout<<"sizeof(char)="<<sizeof(char)<<endl;cout<<"sizeof(int)="<<sizeof(int)<<endl;cout<<"sizeof(float)="<<sizeof(float)<<endl;cout<<"sizeof(double)="<<sizeof(double)<<endl;//用sizeof 计算数组的字节长度char str[]="This is a test.";int a[10];double xy[10];cout<<"sizeof(str)="<<sizeof(str)<<endl;cout<<"sizeof(a)="<<sizeof(a)<<endl;cout<<"sizeof(xy)="<<sizeof(xy)<<endl;//用sizeof 计算自定义类型的长度struct st {short num;float math_grade;float Chinese_grade;float sum_grade;};st student1;cout<<"sizeof(st)="<<sizeof(st)<<endl;cout<<"sizeof(student1)="<<sizeof(student1)<<endl;}#include <iostream.h>main(){//声明变量语句中使用顺序运算int x, y;//计算中使用顺序运算x=50;y=(x=x-5, x/5);cout<<"x="<<x<<endl;cout<<"y="<<y<<endl;}#include <iostream.h>main(){//测试表达式类型的转换int n=100,m;double x=3.791,y;cout<<"n*x="<<n*x<<endl;//赋值类型转换m=x;y=n;cout<<"m="<<m<<endl;cout<<"y="<<y<<endl;//强制类型转换cout<<"int(x)="<<int(x)<<endl;cout<<"(int)x="<<(int)x<<endl;cout<<"int(1.732+x)="<<int(1.732+x)<<endl;cout<<"(int)1.732+x="<<(int)1.723+x<<endl;cout<<"double(100)="<<double(100)<<endl;}#include <iostream.h>main(){float a,b,s;cout<<"a b"<<endl;cin>>a>>b; //利用cin从键盘上为变量 a,b 赋值s=a;if (a<b) {s=b; //if语句中只有这一个语句,可省略花括号 }s=s*s; //变量s中保存a,b中较大的一个数的平方 cout<<"s="<<s;}#include <iostream.h>main(){int x,y;cout<<"x=";cin>>x;if (x<=0) { //满足条件执行y=2*x;cout<<"y="<<y; //输出结果}else { //不满足条件执行y=x*x;cout<<"y="<<y; //输出结果}}#include <iostream.h>main(){int a,b,c;int smallest;cout<<"a b c"<<endl;cin>>a>>b>>c;if (a<=b) //外层条件语句{if (a<=c) //内层条件语句smallest=a;elsesmallest=c;}else{if (b<=c) //内层条件语句smallest=b;elsesmallest=c;}cout<<"Smallest="<<smallest<<endl;}#include <iostream.h>main(){int score;//从键盘上输入分数cout<<"score=";cin>>score;//用带else if的条件语句判断处理if (score<0 || score>100){cout<<"The score is out of range!"<<endl; }else if (score>=90)cout<<"Your grade is a A."<<endl;else if (score>=80)cout<<"Your grade is a B."<<endl;else if (score>=70)cout<<"Your grade is a C."<<endl;else if (score>=60)cout<<"Your grade is a D."<<endl;else}#include <iostream.h>main(){int n;cout<<"n=";cin>>n;if (n>=0 && n<=100 &&n%2==0)cout<<"n="<<n<<endl;elsecout<<"The "<<n<<" is out of range!"<<endl; }#include <iostream.h>main(){int a,b,Max;//输入数据cout<<"a=";cin>>a;cout<<"b=";cin>>b;//找出较大值Max=a>b?a:b;cout<<"Max="<<Max<<endl;}#include <iostream.h>main(){int a,b;//输入数据cout<<"a=";cin>>a;cout<<"b=";cin>>b;//除法判断if (b!=0 && a%b==0) {cout<<b<<" divides "<<a<<endl;cout<<"a/b="<<a/b<<endl;}elsecout<<b<<" does not divide "<<a<<endl;}#include <iostream.h>main(){//x,y 为操作数,c为运算符int x,y,z;char c1;cin>>x>>c1>>y; //c1//多路选择语句选择不同表达式计算语句switch(c1) {case '+':cout<<x<<"+"<<y<<"="<<x+y<<endl;case '-':cout<<x<<"-"<<y<<"="<<x-y<<endl;break;case '*':cout<<x<<"*"<<y<<"="<<x*y<<endl;break;case '/':cout<<x<<"/"<<y<<"="<<x/y<<endl;break;case '%':cout<<x<<"%"<<y<<"="<<x%y<<endl;break;default :cout<<"Wrong !"<<endl; //当不符合上述情况时执行本子句 }}#include<iostream.h>float x=365.5; //声明全局变量main() {int x=1,y=2;double w=x+y;{double x=1.414,y=1.732,z=3.14;cout<<"inner:x="<<x<<endl;cout<<"inner:y="<<y<<endl;cout<<"inner:z="<<z<<endl;cout<<"outer:w="<<w<<endl;cout<<"::x="<<::x<<endl; //访问重名的全局变量}cout<<"outer:x="<<x<<endl;cout<<"outer:y="<<y<<endl;cout<<"outer:w="<<w<<endl;//cout<<"inner:z="<<z<<endl;无效cout<<"::x="<<::x<<endl; //访问重名的全局变量}#include<iostream.h>main() {//显示1,2,3 (10)for(int i=1;i<=10;i++)cout<<i<<" ";cout<<endl;//显示10,9,8 (1)for(int j=10;j>=1;j--)cout<<j<<" ";cout<<endl;//显示1,3,5 (9)for(int k=1;k<=10;k=k+2)cout<<k<<" ";cout<<endl;//显示ABC...Zfor(char c='A';c<='Z';c++)cout<<c;cout<<endl;//显示0,0.1,0.2...1.0for(float x=0;x<=1.0;x=x+0.1)cout<<x<<" ";//显示0,0.1,0.2...1.0for(float x1=0;x1<=1.0+0.1/2;x1=x1+0.1) cout<<x1<<" ";cout<<endl;//计算s=1+2+3...+100int s=0;for(int n=1;n<=100;n++)s=s+n;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=1;while(n<=100) {s=s+n;n++;}cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;cout<<"x=";cin>>x;while(x!=0) {sum+=x;cout<<"x=";cin>>x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=0;do {n++;s+=n;}while(n<100);cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;do {cout<<"x=";cin>>x;sum+=x;} while(x!=0);cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算和打印打印乘法九九表cout<<i;for (int j=1;j<=9;j++)cout<<'\t'<<i<<"*"<<j<<"="<<i*j;cout<<endl;}}#include<iostream.h>main(){int x,sum=0;//定义标号L1L1: cout<<"x=";cin>>x;if (x==-1)goto L2; //无条件转移语句,转到L2语句处elsesum+=x;goto L1; //无条件转移语句,转到L1语句处//定义标号L2L2: cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//累加键盘输入的数据double x,sum=0.0;while(1) {cout<<"x=";cin>>x;if (x<=0) break;sum+=x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){int i;for (i=1;i<=20;i++){if (i%3==0) //能被 3 整除的整数,返回进行下次循环 continue;cout<<i<<" ";}cout<<endl;}#include<iostream.h>main(){//声明数组和变量int a[5],i,sum;double avg;//从键盘上循环为数组赋值for (i=0;i<5;i++) {//直接显示数组元素cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;//利用for循环显示数组各元素的值for (i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl;//计算数组元素之和,并显示计算结果sum=a[0]+a[1]+a[2]+a[3]+a[4];cout<<"sum="<<sum<<endl;//利用循环计算数组的累加和for (sum=0,i=0;i<5;i++)sum+=a[i];//显示累加和及平均值cout<<"sum="<<sum<<endl;avg=sum/5.0;cout<<"avg="<<avg<<endl;}#include<iostream.h>main(){int i,max,index,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}// 利用循环遍历数组,找出最大值的元素及其下标 max=a[0];for (i=0;i<=4;i++){if (max<a[i]){max=a[i];index=i;}}cout<<"\nMax="<<max<<" index="<<index;}#include<iostream.h>#define size 5main(){//声明变量int i,j;float t,a[size];//从键盘上为数组赋值for (i=0;i<size;i++){//对数组按从小到大顺序排序for (i=0;i<size-1;i++)for (j=i+1;j<size;j++)if (a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<size;i++)cout<<a[i]<<" ";cout<<endl;//输入要查找的数据int value;int found; //找到为1,否则为0int low,high,mid;for (i=1;i<=3;i++) {cout<<"value=";cin>>value;//二分法查找数组afound=0;low=0;high=size-1;while(low<=high){mid=(high+low)/2;if (a[mid]==value){found=1;break;}if (a[mid]<value)low=mid+1;elsehigh=mid-1;}if (found)cout<<"The valu found at:a["<<mid<<"]="<<a[mid]<<endl; elsecout<<"The "<<value<<" is not found!"<<endl;}}#include<iostream.h>main(){//声明变量int i,j;float t,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){//对数组按从大到小顺序排序for (i=0;i<=3;i++)for (j=i+1;j<=4;j++)if (a[i]<=a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<=4;i++)cout<<a[i]<<" ";}#include<iostream.h>main(){//声明二维数组及变量int a[2][3],i,j;//从键盘上为数组a赋值for (i=0;i<2;i++)for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//显示数组afor (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<a[i][j]<<" ";}cout<<endl;}//找出该数组的最大元素及其下标int h,l,Max=a[0][0];for (i=0;i<2;i++) {for (j=0;j<3;j++){if (Max<a[i][j]) {Max=a[i][j];h=i;l=j;}}}cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl; }#include<iostream.h>main(){//声明字符数组和变量char str[6];//从键盘上输入字符串cout<<"str=";cin>>str;cout<<str<<endl;//按数组和下标变量两种方式显示字符数组cout<<str<<endl;for (i=0;i<6;i++)cout<<str[i];cout<<endl;//字符串反向输出for (i=5;i>=0;i--)cout<<str[i];cout<<endl;//将字符数组变成大写字母后输出for (i=0;i<=5;i++)str[i]-=32; //小写字母转换成大写字母 cout<<str<<endl; //显示字符串}#include<iostream.h>main(){//声明变量和指针变量int a,b,c,*ip;//指针变量ip指向变量aa=100;ip=&a; //使指针变量 ip 指向变量acout<<"a="<<a<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量bip=&b; //使指针变量 ip 指向变量bb=200;cout<<"b="<<b<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量cip=&c; //使指针变量 ip 指向变量b*ip=a+b;cout<<"c="<<c<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;}#include<iostream.h>main(){//声明数组、变量和指针变量int a[2][3],i,j;int* ip;//从键盘上为数组a赋值for (i=0;i<2;i++) //为数组a赋值for (j=0;j<3;j++)。
C经典程序代码大全

//根据半径计算圆的周长和面积#include<iostream.h>constfloatPI=3.1416;//声明常量(只读变量)PI为3.1416floatfCir_L(float);//声明自定义函数fCir_L()的原型floatfCir_S(float);//声明自定义函数fCir_S()的原型//以下是main()函数main(){floatr,l,s;//声明3个变量cout<<"r=";//显示字符串cin>>r; //键盘输入l=fCir_L(r);//计算圆的周长,赋值给变量ls=fCir_S(r);//计算圆的面积,赋值给变量scout<<"l="<<l;//显示计算结果cout<<"\ns="<<s;}//定义计算圆的周长的函数fCir_L()floatfCir_L(floatx){floatz=-1.0;//声明局部变量if(x>=0.0)//如果参数大于0,则计算圆的周长z=2*PI*x;return(z);//返回函数值}//定义计算圆的面积的函数fCir_S()floatfCir_S(floatx){floatz=-1.0;//声明局部变量if(x>=0.0)//如果参数大于0,则计算圆的面积z=PI*x*x;return(z);//返回函数值}/*Program:P1-2.CPPWrittenby:HapDatewritten:02:11:10*/#include<iostream.h>voidmain(void){doubles1,s2,s3;s1=1.5;/*对变量s1赋值*/cout<<"s1="<<s1<<endl;/*对变量s2赋值*/s2=2.5;cout<<"s2="<<s2<<endl;s3=/*对变量s3赋值*/3.5;cout<<"s3="<<s3<<endl;cout<<"s1+s2+s3="<<s1+s2+s3<<endl;//计算并显示//计算并显示cout<<"s1+s2+s3="<<s1+s2+s3<<endl;}#include<iostream.h>main(){doubler=1.0;cout<<"r="<<r<<endl;doublel;l=2*3.1416*r;//计算圆的周长,赋值给变量lcout<<"l="<<l<<endl;//显示圆的周长doubles=3.1416*r*r;//计算圆的面积,赋值给变量s cout<<"s="<<s<<endl;//显示圆的面积cout<<"r=";//显示提示输入的信息cin>>r;//键盘输入l=2*3.1416*r;//计算圆的周长,赋值给变量lcout<<"l="<<l<<endl;//显示圆的周长s=3.1416*r*r;cout<<"s="<<s<<endl;//显示圆的面积}#include<iostream.h>//包含iostream.h头文件voidmain(){//输出字符常量、变量和字符串charc1='A';cout<<'W';cout<<c1<<endl;cout<<"Thisisatest."<<endl;cout<<"------------------"<<endl;//输出整型常量、变量和表达式intn=100;cout<<10;cout<<n;cout<<2*n<<endl;//输出整型表达式cout<<"------------------"<<endl;//输出浮点型常量、变量和表达式doublepi=3.1415926,r=10.0,s=pi*r*r;cout<<pi<<endl;cout<<r;cout<<s;cout<<2*r*pi<<endl;//输出浮点型表达式cout<<"------------------"<<endl;//一个cout可以输出多项数据cout<<'W'<<""<<c1<<endl;cout<<"Thisisatest."<<endl;cout<<"pi="<<pi<<"r="<<r<<"s="<<s<<endl;}#include<iostream.h>//包含iostream.h头文件main(){//输入输出字符charc;cin>>c;cout<<"c="<<c<<endl;//输入输出整型数据intn;cin>>n;cout<<"n="<<n<<endl;//输入输出浮点型数据doublex;cin>>x;cout<<"x="<<x<<endl;//输入提示cout<<"n=";cin>>n;cout<<"n="<<n<<endl;//多项输入cout<<"cnx"<<endl;cin>>c>>n>>x;cout<<"c="<<c<<"n="<<n<<"x="<<x<<endl;}#include<iostream.h>//包含iostream.h头文件main(){//声明整型变量inta,b;//从键盘上为整型变量赋值cout<<"a=";cin>>a;cout<<"b=";cin>>b;//整型数的算术运算cout<<a<<"+"<<b<<"="<<a+b<<endl;cout<<a<<"-"<<b<<"="<<a-b<<endl;cout<<a<<"*"<<b<<"="<<a*b<<endl;cout<<a<<"/"<<b<<"="<<a/b<<endl;cout<<a<<"%"<<b<<"="<<a%b<<endl;//测试溢出shortn=32767,m;//n取short类型的最大值cout<<"n="<<n<<endl;m=n+1;//引起溢出cout<<"n+1="<<m<<endl;}#include<iostream.h>//包含iostream.h头文件main(){//声明变量,并初始化inta=010,b=10,c=0X10;//以十进制形式显示数据cout<<"DEC:";cout<<"a="<<a;cout<<"b="<<b;cout<<"c="<<c<<endl;//以八进制形式显示数据cout<<"OCT:";cout<<oct;//指定八进制输出cout<<"a="<<a;cout<<"b="<<b;cout<<"c="<<c<<endl;//以十六进制形式显示数据cout<<"HEX:";cout<<hex;//指定十六进制输出cout<<"a="<<a;cout<<"b="<<b;cout<<"c="<<c<<endl;//八、十和十六进制数混合运算并输出cout<<"a+b+c=";cout<<dec;//恢复十进制输出cout<<a+b+c<<endl;//测试八、十和十六进制输入cout<<"DEC:a=";cin>>a;cout<<"OCT:b=";cin>>b;cout<<"HEX:a=";cin>>c;cout<<"DEC:"<<dec<<endl;//指定十进制输出cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;cout<<"c="<<c<<endl;}#include<iostream.h>//包含iostream.h头文件#include<iomanip.h>//iomanip.h头文件包含setprecision()的定义main(){//float型变量的声明、输入、计算和输出floatfx,fy;cout<<"fx=";cin>>fx;cout<<"fy=";cin>>fy;cout<<fx<<"+"<<fy<<"="<<fx+fy<<endl;cout<<fx<<"-"<<fy<<"="<<fx-fy<<endl;cout<<fx<<"*"<<fy<<"="<<fx*fy<<endl;cout<<fx<<"/"<<fy<<"="<<fx/fy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl;Error!//double型变量的声明、输入、计算和输出floatdx,dy;cout<<"dx=";cin>>dx;cout<<"dy=";cin>>dy;cout<<dx<<"+"<<dy<<"="<<dx+dy<<endl;cout<<dx<<"-"<<dy<<"="<<dx-dy<<endl;cout<<dx<<"*"<<dy<<"="<<dx*dy<<endl;cout<<dx<<"/"<<dy<<"="<<dx/dy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl;Error!//测试float和double类型数据的有效位fx=10.0;fy=6.0;floatfz=fx/fy;dx=10.0;dy=6.0;doubledz=dx/dy;cout<<"fz=";cout<<setprecision(20)<<fx<<"/"<<fy<<"="<<fz<<endl;cout<<"dz=";cout<<setprecision(20)<<dx<<"/"<<dy<<"="<<dz<<endl<<endl;; //float型溢出floatx=3.5e14;cout<<"x="<<x<<endl;cout<<"x*x="<<x*x<<endl;cout<<"x*x*x="<<x*x*x<<endl;}#include<iostream.h>//包含iostream.h头文件main(){//字符类型变量的声明charc1='A';charc2;//字符数据的运算及输出c2=c1+32;cout<<"c1="<<c1<<endl;cout<<"c2="<<c2<<endl;//输出字符及ASCII码cout<<c1<<":"<<int(c1)<<endl;cout<<c2<<":"<<int(c2)<<endl;cout<<'$'<<":"<<int('$')<<endl;//输入字符cout<<"c1 c2"<<endl;cin>>c1>>c2;cout<<"c1="<<c1<<"c2="<<c2<<endl;}#include<iostream.h>//包含iostream.h头文件main(){charc1='\a',TAB='\t';//阵铃一声cout<<c1<<endl;//使用水平制表符cout<<1<<TAB<<2<<TAB<<3<<TAB<<4<<endl;//使用双引号cout<<"Hesaid\"Thankyou\"."<<endl;//使用回车换行cout<<"abc\n"<<"def"<<'\n';}#include<iostream.h>//包含iostream.h头文件main(){//声明bool变量,并初始化boolflag1=false,flag2=true;//输出布尔常量和变量cout<<"false:"<<false<<endl;cout<<"true:"<<true<<endl;cout<<"flag1="<<flag1<<endl;cout<<"flag2="<<flag2<<endl;//布尔变量的赋值和输出intx=1;flag1=x>0;//存放关系运算结果cout<<"flag1="<<flag1<<endl;flag2=flag1;//bool类型变量相互赋值cout<<"flag2="<<flag2<<endl;//布尔变量超界处理flag1=100;cout<<"flag1="<<flag1<<endl;flag2=-100;cout<<"flag2="<<flag2<<endl;}#include<iostream.h>constdoublePI=3.1416;//声明常量(const变量)PI为3.1416 main(){//声明3个变量doubler,l,s;//输入圆的半径cout<<"r=";cin>>r;//计算圆的周长l=2*PI*r;cout<<"l="<<l<<endl;//计算圆的面积s=PI*r*r;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//定义枚举类型,并指定其枚举元素的值enumcolor{RED=3,YELLOW=6,BLUE=9};//声明枚举变量a和b,并为枚举变量a赋初值enumcolora=RED;colorb;//合法,与C语言不同//输出枚举常量cout<<"RED="<<RED<<endl;cout<<"YELLOW="<<YELLOW<<endl;cout<<"BLUE="<<BLUE<<endl;//枚举变量的赋值和输出b=a;a=BLUE;cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;//a=100;错误!//a=6也错误!//枚举变量的关系运算b=BLUE; //枚举变量的赋值运算cout<<"a<b="<<(a<b)<<endl;}#include<iostream.h>constdoublePI=3.1416;//声明常量(const变量)PI为3.1416 main(){//声明3个变量doubler=3,l,s;//计算圆的周长l=2*PI*r;cout<<"l="<<l<<endl;//计算圆的面积s=PI*r*r;cout<<"s="<<s<<endl;//验证赋值误差intil,is;il=l;is=s;cout<<"il="<<il<<endl;cout<<"is="<<is<<endl;}#include<iostream.h>main(){//变量声明charc;doublex,y;//测试自增cout<<"++EandE++:"<<endl;c='B';cout<<"c="<<++c<<endl;//输出c=Cc='B';cout<<"c="<<c++<<endl;//输出c=Bx=1.5;y=5+++x;//加号后的空格不能少cout<<"y="<<y<<endl;//输出y=7.5x=1.5;y=5+x++;cout<<"y="<<y<<endl;//输出y=6.5cout<<"--------------------"<<endl;//测试自减cout<<"--EandE--:"<<endl;c='B';cout<<"c="<<--c<<endl;//输出c=Ac='B';cout<<"c="<<c--<<endl;//输出c=Bx=1.5;y=5+--x;cout<<"y="<<y<<endl;//输出y=5.5x=1.5;y=5+x--;cout<<"y="<<y<<endl;//输出y=6.5}#include<iostream.h>main(){inta=3,b=2;//输出关系表达式cout<<a<b<<endl;cout<<(a<b)<<(a>b)<<(a>=b)<<(a==b)<<(a!=b)<<endl;boolflag=2*a<b+10;cout<<"flag="<<flag;}#include<iostream.h>main(){floata=3.5,b=2.1,c=0;cout<<"a="<<a<<"b="<<b<<"c="<<c<<endl;//与运算cout<<"a&&b="<<(a&&b)<<endl;//输出1cout<<"a&&c="<<(a&&c)<<endl;//输出0//或运算cout<<"a||b="<<(a||b)<<endl;//输出1cout<<"a||c="<<(a||c)<<endl;//输出1//非运算cout<<"!a="<<!a<<endl<<"!c="<<!c<<endl;//输出01//关系运算和逻辑运算boolflag=a>=0&&a<=5;//变量a在[0,5]区间内cout<<"a=>0&&a<=5="<<flag<<endl;//输出1//算术运算、关系运算和逻辑运算cout<<"a+5>2*b+2||a<b+3="<<(a+5>2*b+2||a<b+3)<<endl;//输出1 }#include<iostream.h>main(){//按位与运算cout<<"24&12="<<(24&12)<<endl;//按位异或运算cout<<"24^12="<<(24^12)<<endl;//按位或运算cout<<"24|12="<<(24|12)<<endl;//按位取反运算cout<<"~24="<<(~24)<<endl;//左移位运算cout<<"5<<3="<<(5<<3)<<endl;cout<<"-5<<3="<<(-5<<3)<<endl;//右移位运算cout<<"5>>3="<<(5>>3)<<endl;cout<<"-5>>3="<<(-5>>3)<<endl;}#include<iostream.h>main(){inta=1,b=1,c=3;//显示a,b,c的值cout<<"a="<<a<<"b="<<b<<"c="<<c<<endl;//计算显示(1)b+=a+2*c%5;的结果b+=a+2*c%5; //相当于表达式语句b=b+(a+2*c%5); cout<<"(1)b="<<b<<endl;//计算显示(2)a<<=c-2*b;的结果a=1,b=1,c=3;a<<=c-2*b; //相当于表达式语句a=a<<(c-2*b);cout<<"(2)a="<<a<<endl;//计算显示(3)a*=b=c=3;的结果a=1,b=1,c=3;a*=b=c=3; //相当于语句组c=3;b=c;a=a*b;cout<<"(3)a="<<a<<"b="<<b<<"c="<<c<<endl;//计算显示(4)a+=b+=c;的结果a=1,b=1,c=3;a+=b+=c; //相当于语句组b=b+c;a=a+b;cout<<"(4)a="<<a<<"b="<<b<<"c="<<c<<endl;//计算显示(5)a-=b=++c+2;的结果a=1,b=1,c=3;a-=b=++c+2; //相当于语句组++c;b=b+c+2;a=a-b; cout<<"(5)a="<<a<<"b="<<b<<"c="<<c<<endl;}#include<iostream.h>main(){//用sizeof计算各类种常量的字节长度cout<<"sizeof('$')="<<sizeof('$')<<endl;cout<<"sizeof(1)="<<sizeof(1)<<endl;cout<<"sizeof(1.5)="<<sizeof(1.5)<<endl;cout<<"sizeof(\"Good!\")="<<sizeof("Good!")<<endl; //用sizeof计算各类型变量的字节长度inti=100;charc='A';floatx=3.1416;doublep=0.1;cout<<"sizeof(i)="<<sizeof(i)<<endl;cout<<"sizeof(c)="<<sizeof(c)<<endl;cout<<"sizeof(x)="<<sizeof(x)<<endl;cout<<"sizeof(p)="<<sizeof(p)<<endl;//用sizeof计算表达式的字节长度cout<<"sizeof(x+1.732)="<<sizeof(x+1.732)<<endl;//用sizeof计算各类型的字节长度cout<<"sizeof(char)="<<sizeof(char)<<endl;cout<<"sizeof(int)="<<sizeof(int)<<endl;cout<<"sizeof(float)="<<sizeof(float)<<endl;cout<<"sizeof(double)="<<sizeof(double)<<endl;//用sizeof计算数组的字节长度charstr[]="Thisisatest.";inta[10];doublexy[10];cout<<"sizeof(str)="<<sizeof(str)<<endl;cout<<"sizeof(a)="<<sizeof(a)<<endl;cout<<"sizeof(xy)="<<sizeof(xy)<<endl;//用sizeof计算自定义类型的长度structst{shortnum;floatmath_grade;floatChinese_grade;floatsum_grade;};ststudent1;cout<<"sizeof(st)="<<sizeof(st)<<endl;cout<<"sizeof(student1)="<<sizeof(student1)<<endl;}#include<iostream.h>main(){//声明变量语句中使用顺序运算intx,y;//计算中使用顺序运算x=50;y=(x=x-5,x/5);cout<<"x="<<x<<endl;cout<<"y="<<y<<endl;}#include<iostream.h>main(){//测试表达式类型的转换intn=100,m;doublex=3.791,y;cout<<"n*x="<<n*x<<endl;//赋值类型转换m=x;y=n;cout<<"m="<<m<<endl;cout<<"y="<<y<<endl;//强制类型转换cout<<"int(x)="<<int(x)<<endl;cout<<"(int)x="<<(int)x<<endl;cout<<"int(1.732+x)="<<int(1.732+x)<<endl; cout<<"(int)1.732+x="<<(int)1.723+x<<endl; cout<<"double(100)="<<double(100)<<endl;}#include<iostream.h>main(){floata,b,s;cout<<"ab"<<endl;cin>>a>>b; //利用cin从键盘上为变量a,b赋值s=a;if(a<b){s=b;//if语句中只有这一个语句,可省略花括号}s=s*s;//变量s中保存a,b中较大的一个数的平方cout<<"s="<<s;}#include<iostream.h>main(){intx,y;cout<<"x=";cin>>x;if(x<=0){//满足条件执行y=2*x;cout<<"y="<<y;//输出结果}else{//不满足条件执行y=x*x;cout<<"y="<<y;//输出结果}}#include<iostream.h>main(){inta,b,c;intsmallest;cout<<"abc"<<endl;cin>>a>>b>>c;if(a<=b)//外层条件语句{if(a<=c)//内层条件语句smallest=a;elsesmallest=c;}else{if(b<=c)//内层条件语句smallest=b;elsesmallest=c;}cout<<"Smallest="<<smallest<<endl;}#include<iostream.h>main(){intscore;//从键盘上输入分数cout<<"score=";cin>>score;//用带elseif的条件语句判断处理if(score<0||score>100){cout<<"Thescoreisoutofrange!"<<endl;}elseif(score>=90)cout<<"YourgradeisaA."<<endl;elseif(score>=80)cout<<"YourgradeisaB."<<endl;elseif(score>=70)cout<<"YourgradeisaC."<<endl;elseif(score>=60)cout<<"YourgradeisaD."<<endl;elsecout<<"YourgradeisaE."<<endl;}#include<iostream.h>main(){intn;cout<<"n=";cin>>n;if(n>=0&&n<=100&&n%2==0)cout<<"n="<<n<<endl;elsecout<<"The"<<n<<"isoutofrange!"<<endl; }#include<iostream.h>main(){inta,b,Max;//输入数据cout<<"a=";cin>>a;cout<<"b=";cin>>b;//找出较大值Max=a>ba:b;cout<<"Max="<<Max<<endl;}#include<iostream.h>main(){inta,b;//输入数据cout<<"a=";cin>>a;cout<<"b=";cin>>b;//除法判断if(b!=0&&a%b==0){cout<<b<<"divides"<<a<<endl;cout<<"a/b="<<a/b<<endl;}elsecout<<b<<"doesnotdivide"<<a<<endl;}#include<iostream.h>main(){//x,y为操作数,c为运算符intx,y,z;charc1;cin>>x>>c1>>y;//c1//多路选择语句选择不同表达式计算语句switch(c1){case'+':cout<<x<<"+"<<y<<"="<<x+y<<endl;break;case'-':cout<<x<<"-"<<y<<"="<<x-y<<endl;break;case'*':cout<<x<<"*"<<y<<"="<<x*y<<endl;break;case'/':cout<<x<<"/"<<y<<"="<<x/y<<endl;break;case'%':cout<<x<<"%"<<y<<"="<<x%y<<endl;break;default:cout<<"Wrong!"<<endl;//当不符合上述情况时执行本子句}}#include<iostream.h>floatx=365.5;//声明全局变量main(){intx=1,y=2;doublew=x+y;{doublex=1.414,y=1.732,z=3.14;cout<<"inner:x="<<x<<endl;cout<<"inner:y="<<y<<endl;cout<<"inner:z="<<z<<endl;cout<<"outer:w="<<w<<endl;cout<<"::x="<<::x<<endl;//访问重名的全局变量}cout<<"outer:x="<<x<<endl;cout<<"outer:y="<<y<<endl;cout<<"outer:w="<<w<<endl;//cout<<"inner:z="<<z<<endl;无效cout<<"::x="<<::x<<endl;//访问重名的全局变量}#include<iostream.h>main(){//显示1,2,3 (10)for(inti=1;i<=10;i++)cout<<i<<"";cout<<endl;//显示10,9,8 (1)for(intj=10;j>=1;j--)cout<<j<<"";cout<<endl;//显示1,3,5 (9)for(intk=1;k<=10;k=k+2)cout<<k<<"";cout<<endl;//显示ABC...Zfor(charc='A';c<='Z';c++)cout<<c;cout<<endl;//显示0,0.1,0.2...1.0for(floatx=0;x<=1.0;x=x+0.1)cout<<x<<"";cout<<endl;//显示0,0.1,0.2...1.0for(floatx1=0;x1<=1.0+0.1/2;x1=x1+0.1)cout<<x1<<"";cout<<endl;//计算s=1+2+3...+100ints=0;for(intn=1;n<=100;n++)s=s+n;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100ints=0,n=1;while(n<=100){s=s+n;n++;}cout<<"s="<<s<<endl;//累加键盘输入的数据doublex,sum=0.0;cout<<"x=";cin>>x;while(x!=0){sum+=x;cout<<"x=";cin>>x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100ints=0,n=0;do{n++;s+=n;}while(n<100);cout<<"s="<<s<<endl;//累加键盘输入的数据doublex,sum=0.0;do{cout<<"x=";cin>>x;sum+=x;}while(x!=0);cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算和打印打印乘法九九表for(inti=1;i<=9;i++){cout<<i;for(intj=1;j<=9;j++)cout<<'\t'<<i<<"*"<<j<<"="<<i*j;cout<<endl;}}#include<iostream.h>main(){intx,sum=0;//定义标号L1L1:cout<<"x=";cin>>x;if(x==-1)gotoL2;//无条件转移语句,转到L2语句处elsesum+=x;gotoL1;//无条件转移语句,转到L1语句处//定义标号L2L2:cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//累加键盘输入的数据doublex,sum=0.0;while(1){cout<<"x=";cin>>x;if(x<=0)break;sum+=x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){inti;for(i=1;i<=20;i++){if(i%3==0)//能被3整除的整数,返回进行下次循环continue;cout<<i<<"";}cout<<endl;}#include<iostream.h>main(){//声明数组和变量inta[5],i,sum;doubleavg;//从键盘上循环为数组赋值for(i=0;i<5;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//直接显示数组元素cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;//利用for循环显示数组各元素的值for(i=0;i<5;i++)cout<<a[i]<<"";cout<<endl;//计算数组元素之和,并显示计算结果sum=a[0]+a[1]+a[2]+a[3]+a[4];cout<<"sum="<<sum<<endl;//利用循环计算数组的累加和for(sum=0,i=0;i<5;i++)sum+=a[i];//显示累加和及平均值cout<<"sum="<<sum<<endl;avg=sum/5.0;cout<<"avg="<<avg<<endl;}#include<iostream.h>main(){inti,max,index,a[5];//从键盘上为数组赋值for(i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//利用循环遍历数组,找出最大值的元素及其下标max=a[0];for(i=0;i<=4;i++){if(max<a[i]){max=a[i];index=i;}}cout<<"\nMax="<<max<<"index="<<index;}#include<iostream.h>#definesize5main(){//声明变量inti,j;floatt,a[size];//从键盘上为数组赋值for(i=0;i<size;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//对数组按从小到大顺序排序for(i=0;i<size-1;i++)for(j=i+1;j<size;j++)if(a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for(i=0;i<size;i++)cout<<a[i]<<"";cout<<endl;//输入要查找的数据intvalue;intfound;//找到为1,否则为0int low,high,mid;for(i=1;i<=3;i++){cout<<"value=";cin>>value;//二分法查找数组afound=0;low=0;high=size-1;while(low<=high){mid=(high+low)/2;if(a[mid]==value){found=1;break;}if(a[mid]<value)low=mid+1;elsehigh=mid-1;}if(found)cout<<"Thevalufoundat:a["<<mid<<"]="<<a[mid]<<endl; elsecout<<"The"<<value<<"isnotfound!"<<endl;}}#include<iostream.h>main(){//声明变量for(i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//对数组按从大到小顺序排序for(i=0;i<=3;i++)for(j=i+1;j<=4;j++)if(a[i]<=a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for(i=0;i<=4;i++)cout<<a[i]<<"";}#include<iostream.h>main(){//声明二维数组及变量inta[2][3],i,j;//从键盘上为数组a赋值for(i=0;i<2;i++)for(j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//显示数组afor(i=0;i<2;i++){for(j=0;j<3;j++){cout<<a[i][j]<<"";}cout<<endl;}//找出该数组的最大元素及其下标inth,l,Max=a[0][0];for(i=0;i<2;i++){for(j=0;j<3;j++){if(Max<a[i][j]){Max=a[i][j];h=i;l=j;}}}cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl; }#include<iostream.h>main(){//声明字符数组和变量charstr[6];cin>>str;cout<<str<<endl;//按数组和下标变量两种方式显示字符数组cout<<str<<endl;for(i=0;i<6;i++)cout<<str[i];cout<<endl;//字符串反向输出for(i=5;i>=0;i--)cout<<str[i];cout<<endl;//将字符数组变成大写字母后输出for(i=0;i<=5;i++)str[i]-=32; //小写字母转换成大写字母cout<<str<<endl; //显示字符串}#include<iostream.h>main(){//声明变量和指针变量inta,b,c,*ip;//指针变量ip指向变量aa=100;ip=&a;//使指针变量ip指向变量acout<<"a="<<a<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量bip=&b;//使指针变量ip指向变量bb=200;cout<<"b="<<b<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量cip=&c;//使指针变量ip指向变量b*ip=a+b;cout<<"c="<<c<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;}#include<iostream.h>main(){//声明数组、变量和指针变量inta[2][3],i,j;int*ip;//从键盘上为数组a赋值for(i=0;i<2;i++)//为数组a赋值for(j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//利用下标变量显示数组afor(i=0;i<2;i++){for(j=0;j<3;j++){。
C 经典程序代码大全

C 经典程序代码大全#include const float PI=3.1416; //声明常量(只读变量)PI为3.1416 float fCir_L(float); //声明自定义函数fCir_L()的原型 float fCir_S(float); //声明自定义函数fCir_S()的原型 //以下是main()函数 main(){ float r,l,s; //声明3个变量 cout>r; //键盘输入l=fCir_L(r); //计算圆的周长,赋值给变量l s=fCir_S(r); //计算圆的面积,赋值给变量s cout=0.0)//如果参数大于0,则计算圆的周长 z=2*PI*x; return(z); //返回函数值 } //定义计算圆的面积的函数fCir_S() float fCir_S(float x){ float z=-1.0; //声明局部变量 if (x>=0.0)//如果参数大于0,则计算圆的面积 z=PI*x*x; return(z); //返回函数值 } /* Program: P1-2.CPP Written by: Hap Date written: 02:11:10 */#include void main(void){ double s1,s2,s3; s1=1.5; /* 对变量s1赋值*/ cout main(){ double r=1.0; cout>r; //键盘输入 l=2*3.1416*r; //计算圆的周长,赋值给变量l cout //包含iostream.h头文件 void main(){ //输出字符常量.变量和字符串 char c1= A ; cout //包含iostream.h头文件 main(){ //输入输出字符 char c; cin>>c; cout>n; cout>x; cout>n; cout>c>>n>>x; cout //包含iostream.h头文件 main() { //声明整型变量 int a,b; //从键盘上为整型变量赋值cout>a; cout>b; //整型数的算术运算 cout //包含iostream.h 头文件 main(){ //声明变量,并初始化 int a=010,b=10,c=0X10; //以进制形式显示数据 cout>a; cout>b; cout>c; cout //包含iostream.h头文件 #include // iomanip.h头文件包含setprecision()的定义 main(){ //float型变量的声明.输入.计算和输出 float fx,fy; cout>fx; cout>fy; cout>dx; cout>dy; cout //包含iostream.h 头文件 main(){ //字符类型变量的声明 char c1= A ; char c2; //字符数据的运算及输出 c2=c1+32; cout>c1>>c2; cout //包含iostream.h头文件 main(){ char c1= \a ,TAB= \t ; //阵铃一声 cout //包含iostream.h头文件 main(){ //声明bool变量,并初始化 boolflag1=false,flag2=true; //输出布尔常量和变量 cout0; //存放关系运算结果 cout const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){ //声明3个变量 double r,l,s; //输入圆的半径 cout>r; //计算圆的周长 l=2*PI*r; cout main(){ //定义枚举类型,并指定其枚举元素的值 enum color { RED=3, YELLOW=6, BLUE=9 }; //声明枚举变量a和b,并为枚举变量a赋初值 enum color a=RED; color b; //合法,与C语言不同 // 输出枚举常量 cout const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){ //声明3个变量 double r=3,l,s; //计算圆的周长l=2*PI*r; cout main(){ //变量声明 char c; double x,y; //测试自增 cout main(){ int a=3, b=2; //输出关系表达式 coutb)=b)main(){ float a=3.5,b=2.1,c=0; cout=0 //显示a,b,c的值 cout main(){ //用 sizeof 计算各类种常量的字节长度 cout main(){ //声明变量语句中使用顺序运算 int x, y; //计算中使用顺序运算 x=50; y=(x=x-5, x/5); cout main(){ //测试表达式类型的转换 int n=100,m; double x=3.791,y; cout main(){ float a,b,s; cout>a>>b; //利用cin从键盘上为变量a,b 赋值 s=a; if (a main(){ int x,y; cout>x; if (x main(){ int a,b,c; int smallest; cout>a>>b>>c; if (a main() { int score; //从键盘上输入分数 cout>score; //用带else if的条件语句判断处理 if (score100){ cout=90)cout=80)cout=70)cout=60)cout main(){ int n; cout>n; if (n>=0 //输入数据 cout>a; cout>b; //找出较大值 Max=a>b?a:b; cout main(){ int a,b; //输入数据 cout>a; cout>b; //除法判断 if (b!=0 char c1; cin>>x>>c1>>y; //c1。
c经典代码大全

#include <iostream.h> //包含iostream.h头文件main(){//声明变量,并初始化int a=010,b=10,c=0X10;//以十进制形式显示数据cout<<"DEC:";cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以八进制形式显示数据cout<<"OCT:";cout<<oct; //指定八进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以十六进制形式显示数据cout<<"HEX:";cout<<hex; //指定十六进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//八、十和十六进制数混合运算并输出cout<<"a+b+c=";cout<<dec; //恢复十进制输出cout<<a+b+c<<endl;//测试八、十和十六进制输入cout<<"DEC:a="; cin>>a;cout<<"OCT:b="; cin>>b;cout<<"HEX:a="; cin>>c;cout<<"DEC:"<<dec<<endl; //指定十进制输出cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;cout<<"c="<<c<<endl;}cin>>dx;cout<<"dy=";cin>>dy;cout<<dx<<"+"<<dy<<"="<<dx+dy<<endl; cout<<dx<<"-"<<dy<<"="<<dx-dy<<endl; cout<<dx<<"*"<<dy<<"="<<dx*dy<<endl;cout<<dx<<"/"<<dy<<"="<<dx/dy<<endl<< endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!//测试float和double类型数据的有效位fx=10.0;fy=6.0;float fz=fx/fy;dx=10.0;dy=6.0; double dz=dx/dy;cout<<"fz=";cout<<setprecision(20)<<fx<<"/"<<fy<< "="<<fz<<endl;cout<<"dz=";cout<<setprecision(20)<<dx<<"/"<<dy<< "="<<dz<<endl<<endl;;//float型溢出float x=3.5e14;cout<<"x="<<x<<endl;cout<<"x*x="<<x*x<<endl;cout<<"x*x*x="<<x*x*x<<endl;}#include <iostream.h>main(){//x,y 为操作数,c为运算符int x,y,z;char c1;cin>>x>>c1>>y; //c1//多路选择语句选择不同表达式计算语句switch(c1) {case'+':cout<<x<<"+"<<y<<"="<<x+y<<endl; break;case'-':cout<<x<<"-"<<y<<"="<<x-y<<endl; break;case'*':cout<<x<<"*"<<y<<"="<<x*y<<endl; break;case'/':cout<<x<<"/"<<y<<"="<<x/y<<endl; break;case'%':cout<<x<<"%"<<y<<"="<<x%y<<endl; break;default :cout<<"Wrong !"<<endl; //当不符合上述情况时执行本子句}}#include<iostream.h>float x=365.5; //声明全局变量main() {int x=1,y=2;double w=x+y;{double x=1.414,y=1.732,z=3.14; cout<<"inner:x="<<x<<endl;cout<<"inner:y="<<y<<endl;cout<<"inner:z="<<z<<endl;cout<<"outer:w="<<w<<endl;cout<<"::x="<<::x<<endl; //访问重名的全局变量}cout<<"outer:x="<<x<<endl;cout<<"outer:y="<<y<<endl;cout<<"outer:w="<<w<<endl;//cout<<"inner:z="<<z<<endl;无效 cout<<"::x="<<::x<<endl; //访问重名的全局变量}#include<iostream.h>main() {//显示1,2,3 (10)for(int i=1;i<=10;i++)cout<<i<<" ";cout<<endl;//显示10,9,8 (1)for(int j=10;j>=1;j--)cout<<j<<" ";cout<<endl;//显示1,3,5 (9)for(int k=1;k<=10;k=k+2)cout<<k<<" ";cout<<endl;//显示ABC...Zfor(char c='A';c<='Z';c++)cout<<c;cout<<endl;//显示0,0.1,0.2...1.0for(float x=0;x<=1.0;x=x+0.1)cout<<x<<" ";cout<<endl;//显示0,0.1,0.2...1.0for(floatx1=0;x1<=1.0+0.1/2;x1=x1+0.1)cout<<x1<<" ";cout<<endl;//计算s=1+2+3...+100int s=0;for(int n=1;n<=100;n++)s=s+n;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=1;while(n<=100) {s=s+n;n++;}cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;cout<<"x=";cin>>x;while(x!=0) {sum+=x;cout<<"x=";cin>>x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=0;do {n++;s+=n;}while(n<100);cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;do {cout<<"x=";cin>>x;sum+=x;} while(x!=0);cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算和打印打印乘法九九表for (int i=1;i<=9;i++) {cout<<i;for (int j=1;j<=9;j++)cout<<'\t'<<i<<"*"<<j<<"="<<i*j;cout<<endl;}}#include<iostream.h>main(){int x,sum=0;//定义标号L1L1: cout<<"x=";cin>>x;if (x==-1)goto L2; //无条件转移语句,转到L2语句处elsesum+=x;goto L1; //无条件转移语句,转到L1语句处//定义标号L2L2: cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//累加键盘输入的数据double x,sum=0.0;while(1) {cout<<"x=";cin>>x;if (x<=0) break;sum+=x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){int i;for (i=1;i<=20;i++){if (i%3==0) //能被 3 整除的整数,返回进行下次循环continue;cout<<i<<" ";}cout<<endl;}#include<iostream.h>main(){//声明数组和变量int a[5],i,sum;double avg;//从键盘上循环为数组赋值for (i=0;i<5;i++) {cout<<"a["<<i<<"]=";cin>>a[i];}//直接显示数组元素cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<e ndl;//利用for循环显示数组各元素的值 for (i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl;//计算数组元素之和,并显示计算结果 sum=a[0]+a[1]+a[2]+a[3]+a[4];cout<<"sum="<<sum<<endl;//利用循环计算数组的累加和for (sum=0,i=0;i<5;i++)sum+=a[i];//显示累加和及平均值cout<<"sum="<<sum<<endl;avg=sum/5.0;cout<<"avg="<<avg<<endl;}#include<iostream.h>main(){int i,max,index,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}// 利用循环遍历数组,找出最大值的元素及其下标max=a[0];for (i=0;i<=4;i++){if (max<a[i]) {max=a[i];index=i;}}cout<<"\nMax="<<max<<"index="<<index;}#include<iostream.h>#define size 5main(){//声明变量int i,j;float t,a[size];//从键盘上为数组赋值for (i=0;i<size;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//对数组按从小到大顺序排序for (i=0;i<size-1;i++)for (j=i+1;j<size;j++)if (a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<size;i++)cout<<a[i]<<" ";cout<<endl;//输入要查找的数据int value;int found; //找到为1,否则为0int low,high,mid;for (i=1;i<=3;i++) {cout<<"value=";cin>>value;//二分法查找数组afound=0;low=0;high=size-1;while(low<=high){mid=(high+low)/2;if (a[mid]==value){found=1;break;}if (a[mid]<value)low=mid+1;elsehigh=mid-1;}if (found)cout<<"The valu foundat:a["<<mid<<"]="<<a[mid]<<endl;elsecout<<"The "<<value<<" is not found!"<<endl;}}#include<iostream.h>main(){//声明变量int i,j;float t,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//对数组按从大到小顺序排序for (i=0;i<=3;i++)for (j=i+1;j<=4;j++)if (a[i]<=a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<=4;i++)cout<<a[i]<<" ";}#include<iostream.h>main(){//声明二维数组及变量int a[2][3],i,j;//从键盘上为数组a赋值for (i=0;i<2;i++)for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//显示数组afor (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<a[i][j]<<" ";}cout<<endl;}//找出该数组的最大元素及其下标int h,l,Max=a[0][0];for (i=0;i<2;i++) {for (j=0;j<3;j++){if (Max<a[i][j]) {Max=a[i][j];h=i; l=j;}}}cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="< <a[h][l]<<endl;}#include<iostream.h>main(){//声明字符数组和变量char str[6];int i;//从键盘上输入字符串cout<<"str=";cin>>str;cout<<str<<endl;//按数组和下标变量两种方式显示字符数组cout<<str<<endl;for (i=0;i<6;i++)cout<<str[i];cout<<endl;//字符串反向输出for (i=5;i>=0;i--)cout<<str[i];cout<<endl;//将字符数组变成大写字母后输出for (i=0;i<=5;i++)str[i]-=32; //小写字母转换成大写字母cout<<str<<endl; //显示字符串}#include<iostream.h>main(){//声明变量和指针变量int a,b,c,*ip;//指针变量ip指向变量aa=100;ip=&a; //使指针变量 ip 指向变量acout<<"a="<<a<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量bip=&b; //使指针变量 ip 指向变量bb=200;cout<<"b="<<b<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量cip=&c; //使指针变量 ip 指向变量b*ip=a+b;cout<<"c="<<c<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;}#include<iostream.h>main(){//声明数组、变量和指针变量int a[2][3],i,j;int* ip;//从键盘上为数组a赋值for (i=0;i<2;i++) //为数组a赋值 for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//利用下标变量显示数组afor (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<a[i][j]<<" ";}cout<<endl;}//利用指针变量显示数组aip=&a[0][0];for (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cout<<ip<<" ";cout<<*ip<<endl;ip++;}}}#include<iostream.h>main(){//声明数组、变量和指针变量int a[]={1,2,3,4,5,6};int *ip1,*ip2;//测试指针的赋值运算ip1=a;ip2=ip1;cout<<"*ip1="<<(*ip1)<<endl;cout<<"*ip2="<<(*ip2)<<endl;//测试指针的自增自减运算和组合运算ip1++;ip2+=4;cout<<"*ip1="<<(*ip1)<<endl;cout<<"*ip2="<<(*ip2)<<endl;//测试指针变量之间的关系运算int n=ip2>ip1;cout<<"ip2>ip1="<<n<<endl;cout<<"ip2!=NULL="<<(ip2!=NULL)<<endl ; //指针变量之间的减法n=ip2-ip1;cout<<"ip2-ip1="<<n<<endl;}#include<iostream.h>main(){//声明字符型数组和指针变量char str[10];char *strip=str;//输入输出cout<<"str=";cin>>str; //用字符数组输入字符串cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;cout<<"strip=";cin>>strip; //用字符指针变量输入字符串cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;//利用指针变量改变其指向字符串的内容*(strip+2)='l';cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;//动态为字符型指针变量分配内存strip=new char(100);cout<<"strip=";cin>>strip; //用字符指针变量输入字符串cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;}#include<iostream.h>main(){// 声明用于存放运动员号码的数组int h[]={1001,1002,1003,1004};// 声明用于存放运动员成绩的数组float x[]={12.3,13.1,11.9,12.1}; //声明用于存放运动姓名的字符型指针数组char *p[]={"Wang hua","Zhang jian","Li wei","Hua ming"};//i,j,it是用做循环控制变量和临时变量int i,j,it;//ft 用做暂存变量float ft;//pt为字符型指针变量用做暂存指针变量char *pt;//用选择法对数组x进行排序,并相应调整数组h和p中的数据for (i=0;i<=3;i++)for (j=i+1;j<=3;j++)if (x[i]>=x[j]) {ft=x[i],x[i]=x[j],x[j]=ft;it=h[i],h[i]=h[j],h[j]=it;pt=p[i],p[i]=p[j],p[j]=pt;}//以下打印排序结果for (i=0;i<=3;i++)cout<<h[i]<<" ,"<<p[i]<<" ,"<<x[i]<<e ndl;}#include<iostream.h>main(){//声明指针数组char*colors[]={"Red","Blue","Yellow","Gre en"};//指向指针的指针变量char **pt;//通过指向指针的变量访问其指向的内容pt=colors;for (int i=0;i<=3;i++) {cout<<"pt="<<pt<<endl;cout<<"*pt="<<*pt<<endl;cout<<"**pt="<<**pt<<endl;pt++;}}#include<iostream.h>main(){//定义结构类型struct books{char title[20];char author[15];int pages;float price;} ;//声明结构变量struct books Zbk={"VC++ ","Zhang",295,35.5};books Wbk;//对结构变量的输出cout<<"Zbk:"<<endl;cout<<Zbk.title <<endl;cout<<Zbk.author<<endl;cout<<Zbk.pages<<endl;cout<<Zbk.price<<endl;cout<<"--------------------"<<endl;//对结构成员的运算Zbk.pages+=10;Zbk.price+=0.5;cout<<"Zbk.pages="<<Zbk.pages<<endl; cout<<"Zbk.price="<<Zbk.price<<endl;cout<<"--------------------"<<endl;//对结构变量的输入输出cout<<"Wbk.title =";cin>>Wbk.title;cout<<"Wbk.author=";cin>>Wbk.author;cout<<"Wbk.pages=";cin>>Wbk.pages;cout<<"Wbk.price=";cin>>Wbk.price;cout<<"Wbk:"<<endl;cout<<Wbk.title <<endl;cout<<Wbk.author<<endl;cout<<Wbk.pages<<endl;cout<<Wbk.price<<endl;cout<<"--------------------"<<endl;//结构变量之间的相互赋值books temp;temp=Wbk;cout<<"temp:"<<endl;cout<<temp.title<<endl;cout<<temp.author<<endl;cout<<temp.pages<<endl;cout<<temp.price<<endl;}#include<iostream.h>main(){int i;//定义结构类型struct student {int num;char name[10];float maths;float physics;float chemistry;double total;};//声明结构数组ststudent st[3];//从键盘上为结构数组输入值cout<<" num name maths physics chemistry "<<endl;for (i=0;i<3;i++){cout<<i+1<<" ";cin>>st[i].num;cin>>st[i].name;cin>>st[i].maths;cin>>st[i].physics;cin>>st[i].chemistry;}//计算每个学生的总成绩for (i=0;i<3;i++)st[i].total=st[i].maths+st[i].physics +st[i].chemistry;//输出结构数组各元素的值for (i=0;i<3;i++){cout<<"st["<<i<<"]: ";cout<<st[i].num<<'\t';cout<<st[i].name<<'\t';cout<<st[i].maths<<'\t';cout<<st[i].physics<<'\t';cout<<st[i].chemistry<<'\t';cout<<st[i].total<<endl;}}#include<iostream.h>main(){//定义结构类型struct human {char name[10];int sex;int age;};//声明结构变量和结构指针变量,并初始化struct human x={"WangPing",1,30},*p=NULL;//结构指针变量指向对象p=&x;//显示结构变量的值cout<<"="<<<<endl;cout<<"x.sex="<<x.sex<<endl;cout<<"x.age="<<x.age<<endl;//利用结构指针显示结构对象中的数据cout<<"(*p).name="<<(*p).name<<endl;cout<<"(*p).sex="<<(*p).sex<<endl;cout<<"(*p).age="<<(*p).age<<endl;cout<<"p->name="<<p->name<<endl;cout<<"p->sex="<<p->sex<<endl;cout<<"p->age="<<p->age<<endl;//通过结构指针为结构对象输入数据cout<<"name:";cin>>(*p).name;cout<<"sex:";cin>>(*p).sex;cout<<"age:";cin>>(*p).age;//显示结构变量的值cout<<"="<<<<endl;cout<<"x.sex="<<x.sex<<endl;cout<<"x.age="<<x.age<<endl;}include<iostream.h>main(){//定义结构类型struct human {char name[10];int sex; int age;};//声明结构变量和结构指针,并初始化 struct human x={"WangPing",1,30},*p=&x;//利用结构指针显示结构中的数据cout<<"(*p).name="<<(*p).name<<endl; cout<<"(*p).sex="<<(*p).sex<<endl;cout<<"(*p).age="<<(*p).age<<endl;cout<<"-------------------------"<<en dl;//利用new运算符为p分配内存p=new human;//从键盘上为p指向的结构对象赋值cout<<"p->name=";cin>>p->name;cout<<"p->sex=";cin>>p->sex;cout<<"p->age=";cin>>p->age;cout<<"-------------------------"<<en dl;//显示p所指结构对象的值cout<<"p->name="<<p->name<<endl;cout<<"p->sex="<<p->sex<<endl;cout<<"p->age="<<p->age<<endl;cout<<"-------------------------"<<en dl;//显示结构变量的值cout<<"="<<<<endl;cout<<"x.sex="<<x.sex<<endl;cout<<"x.age="<<x.age<<endl;//释放p指向的内存delete p;}#include<iostream.h>main(){//定义结构类型struct human {char name[10];int sex;int age;};//声明结构数组和结构指针变量,并初始化humanx[]={{"WeiPing",1,30},{"LiHua",1,25}, {"LiuMin",0,23}},*p=NULL;//用下标变量的输出结构数组的元素for (int i=0;i<3;i++){cout<<x[i].name<<'\t';cout<<x[i].sex<<'\t';cout<<x[i].age<<endl;}cout<<"----------------"<<endl;//用结构指针输出结构数组的元素for (p=x;p<=&x[2];p++){cout<<p->name<<'\t';cout<<p->sex<<'\t';cout<<p->age<<endl;}}#include<iostream.h>main(){//定义一个包含指针成员的结构类型 struct test {char *str;int *ip;} x;//使用结构变量x中的整型指针ipx.ip=new int; //分配1个单元*(x.ip)=100;cout<<"x.ip:"<<x.ip<<'\t'<<*(x.ip)<<e ndl;cout<<"---------------"<<endl;delete x.ip;x.ip=new int[5]; //分配5个单元 for(int i=0;i<5;i++)*(x.ip+i)=100+i;cout<<"x.ip:"<<endl;for(i=0;i<5;i++)cout<<x.ip+i<<'\t'<<(*(x.ip+i))<<endl ;delete x.ip;cout<<"---------------"<<endl;//使用结构变量x中的字符型指针str x.str=new char('A'); //分配1个单元cout<<"x.str:"<<(*x.str)<<endl;cout<<"---------------"<<endl;delete x.str;x.str=new char[5]; //分配多个单元*x.str='G';*(x.str+1)='o';*(x.str+2)='o';*(x.str+3)='d';*(x.str+4)='\0';cout<<"x.str:"<<x.str<<endl;delete x.str;cout<<"---------------"<<endl;//在声明结构变量时初始化test y={"Very Good!",NULL};cout<<"y.str:"<<y.str<<endl;cout<<"y.ip:"<<y.ip<<endl;}#include<iostream.h>main(){//定义date结构struct date{int year;int month;int day;};//定义baby结构struct baby {int num;float weight;date birthday; // date为结构类型};//声明baby结构变量并初始化baby b1={10001,10,{2002,12,25}}; //下列是baby结构变量b1的引用。
c++经典代码大全

#include <iostream.h> //包含iostream.h头文件main(){//声明变量,并初始化int a=010,b=10,c=0X10;//以十进制形式显示数据cout<<"DEC:";cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以八进制形式显示数据cout<<"OCT:";cout<<oct; //指定八进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以十六进制形式显示数据cout<<"HEX:";cout<<hex; //指定十六进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//八、十和十六进制数混合运算并输出cout<<"a+b+c=";cout<<dec; //恢复十进制输出cout<<a+b+c<<endl;//测试八、十和十六进制输入cout<<"DEC:a="; cin>>a;cout<<"OCT:b="; cin>>b;cout<<"HEX:a="; cin>>c;cout<<"DEC:"<<dec<<endl; //指定十进制输出cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;cout<<"c="<<c<<endl;}cin>>dx;cout<<"dy=";cin>>dy;cout<<dx<<"+"<<dy<<"="<<dx+dy<<endl;cout<<dx<<"-"<<dy<<"="<<dx-dy<<endl;cout<<dx<<"*"<<dy<<"="<<dx*dy<<endl;cout<<dx<<"/"<<dy<<"="<<dx/dy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!//测试float和double类型数据的有效位fx=10.0;fy=6.0;float fz=fx/fy;dx=10.0;dy=6.0;double dz=dx/dy;cout<<"fz=";cout<<setprecision(20)<<fx<<"/"<<fy<<"="<<fz<<endl;cout<<"dz=";cout<<setprecision(20)<<dx<<"/"<<dy<<"="<<dz<<endl<<endl;;//float型溢出float x=3.5e14;cout<<"x="<<x<<endl;cout<<"x*x="<<x*x<<endl;cout<<"x*x*x="<<x*x*x<<endl;}#include <iostream.h>main(){//x,y 为操作数,c为运算符int x,y,z;char c1;cin>>x>>c1>>y; //c1//多路选择语句选择不同表达式计算语句switch(c1) {case '+':cout<<x<<"+"<<y<<"="<<x+y<<endl;break;case '-':cout<<x<<"-"<<y<<"="<<x-y<<endl;break;case '*':cout<<x<<"*"<<y<<"="<<x*y<<endl;break;case '/':cout<<x<<"/"<<y<<"="<<x/y<<endl;break;case '%':cout<<x<<"%"<<y<<"="<<x%y<<endl;break;default :cout<<"Wrong !"<<endl; //当不符合上述情况时执行本子句}}#include<iostream.h>float x=365.5; //声明全局变量main() {int x=1,y=2;double w=x+y;{double x=1.414,y=1.732,z=3.14;cout<<"inner:x="<<x<<endl;cout<<"inner:y="<<y<<endl;cout<<"inner:z="<<z<<endl;cout<<"outer:w="<<w<<endl;cout<<"::x="<<::x<<endl; //访问重名的全局变量}cout<<"outer:x="<<x<<endl;cout<<"outer:y="<<y<<endl;cout<<"outer:w="<<w<<endl;//cout<<"inner:z="<<z<<endl;无效cout<<"::x="<<::x<<endl; //访问重名的全局变量}#include<iostream.h>main() {//显示1,2,3 (10)for(int i=1;i<=10;i++)cout<<i<<" ";cout<<endl;//显示10,9,8 (1)for(int j=10;j>=1;j--)cout<<j<<" ";cout<<endl;//显示1,3,5 (9)for(int k=1;k<=10;k=k+2)cout<<k<<" ";cout<<endl;//显示ABC...Zfor(char c='A';c<='Z';c++)cout<<c;cout<<endl;//显示0,0.1,0.2...1.0for(float x=0;x<=1.0;x=x+0.1)cout<<x<<" ";cout<<endl;//显示0,0.1,0.2...1.0for(float x1=0;x1<=1.0+0.1/2;x1=x1+0.1) cout<<x1<<" ";cout<<endl;//计算s=1+2+3...+100int s=0;for(int n=1;n<=100;n++)s=s+n;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=1;while(n<=100) {s=s+n;n++;}cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;cout<<"x=";cin>>x;while(x!=0) {sum+=x;cout<<"x=";cin>>x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=0;do {n++;s+=n;}while(n<100);cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;do {cout<<"x=";cin>>x;sum+=x;} while(x!=0);cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算和打印打印乘法九九表for (int i=1;i<=9;i++) {cout<<i;for (int j=1;j<=9;j++)cout<<'\t'<<i<<"*"<<j<<"="<<i*j;cout<<endl;}}#include<iostream.h>main(){int x,sum=0;//定义标号L1L1: cout<<"x=";cin>>x;if (x==-1)goto L2; //无条件转移语句,转到L2语句处elsesum+=x;goto L1; //无条件转移语句,转到L1语句处//定义标号L2L2: cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//累加键盘输入的数据double x,sum=0.0;while(1) {cout<<"x=";cin>>x;if (x<=0) break;sum+=x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){int i;for (i=1;i<=20;i++){if (i%3==0) //能被3 整除的整数,返回进行下次循环continue;cout<<i<<" ";}cout<<endl;}#include<iostream.h>main(){//声明数组和变量int a[5],i,sum;double avg;//从键盘上循环为数组赋值for (i=0;i<5;i++) {cout<<"a["<<i<<"]=";cin>>a[i];}//直接显示数组元素cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;//利用for循环显示数组各元素的值for (i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl;//计算数组元素之和,并显示计算结果sum=a[0]+a[1]+a[2]+a[3]+a[4];cout<<"sum="<<sum<<endl;//利用循环计算数组的累加和for (sum=0,i=0;i<5;i++)sum+=a[i];//显示累加和及平均值cout<<"sum="<<sum<<endl;avg=sum/5.0;cout<<"avg="<<avg<<endl;}#include<iostream.h>main(){int i,max,index,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}// 利用循环遍历数组,找出最大值的元素及其下标max=a[0];for (i=0;i<=4;i++){if (max<a[i]){max=a[i];index=i;}}cout<<"\nMax="<<max<<" index="<<index; }#include<iostream.h>#define size 5main(){//声明变量int i,j;float t,a[size];//从键盘上为数组赋值for (i=0;i<size;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//对数组按从小到大顺序排序for (i=0;i<size-1;i++)for (j=i+1;j<size;j++)if (a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<size;i++)cout<<a[i]<<" ";cout<<endl;//输入要查找的数据int value;int found; //找到为1,否则为0int low,high,mid;for (i=1;i<=3;i++) {cout<<"value=";cin>>value;//二分法查找数组afound=0;low=0;high=size-1;while(low<=high){mid=(high+low)/2;if (a[mid]==value){found=1;break;}if (a[mid]<value)low=mid+1;elsehigh=mid-1;}if (found)cout<<"The valu found at:a["<<mid<<"]="<<a[mid]<<endl;elsecout<<"The "<<value<<" is not found!"<<endl;}}#include<iostream.h>main(){//声明变量int i,j;float t,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}//对数组按从大到小顺序排序for (i=0;i<=3;i++)for (j=i+1;j<=4;j++)if (a[i]<=a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<=4;i++)cout<<a[i]<<" ";}#include<iostream.h>main(){//声明二维数组及变量int a[2][3],i,j;//从键盘上为数组a赋值for (i=0;i<2;i++)for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//显示数组afor (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<a[i][j]<<" ";}cout<<endl;}//找出该数组的最大元素及其下标int h,l,Max=a[0][0];for (i=0;i<2;i++) {for (j=0;j<3;j++){if (Max<a[i][j]) {Max=a[i][j];h=i;l=j;}}}cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl; }#include<iostream.h>main(){//声明字符数组和变量char str[6];int i;//从键盘上输入字符串cout<<"str=";cin>>str;cout<<str<<endl;//按数组和下标变量两种方式显示字符数组cout<<str<<endl;for (i=0;i<6;i++)cout<<str[i];cout<<endl;//字符串反向输出for (i=5;i>=0;i--)cout<<str[i];cout<<endl;//将字符数组变成大写字母后输出for (i=0;i<=5;i++)str[i]-=32; //小写字母转换成大写字母cout<<str<<endl; //显示字符串}#include<iostream.h>main(){//声明变量和指针变量int a,b,c,*ip;//指针变量ip指向变量aa=100;ip=&a; //使指针变量ip 指向变量acout<<"a="<<a<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量bip=&b; //使指针变量ip 指向变量b b=200;cout<<"b="<<b<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量cip=&c; //使指针变量ip 指向变量b *ip=a+b;cout<<"c="<<c<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;}#include<iostream.h>main(){//声明数组、变量和指针变量int a[2][3],i,j;int* ip;//从键盘上为数组a赋值for (i=0;i<2;i++) //为数组a赋值for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//利用下标变量显示数组afor (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<a[i][j]<<" ";}cout<<endl;}//利用指针变量显示数组aip=&a[0][0];for (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cout<<ip<<" ";cout<<*ip<<endl;ip++;}}}#include<iostream.h>main(){//声明数组、变量和指针变量int a[]={1,2,3,4,5,6};int *ip1,*ip2;//测试指针的赋值运算ip1=a;ip2=ip1;cout<<"*ip1="<<(*ip1)<<endl;cout<<"*ip2="<<(*ip2)<<endl;//测试指针的自增自减运算和组合运算ip1++;ip2+=4;cout<<"*ip1="<<(*ip1)<<endl;cout<<"*ip2="<<(*ip2)<<endl;//测试指针变量之间的关系运算int n=ip2>ip1;cout<<"ip2>ip1="<<n<<endl;cout<<"ip2!=NULL="<<(ip2!=NULL)<<endl;//指针变量之间的减法n=ip2-ip1;cout<<"ip2-ip1="<<n<<endl;}#include<iostream.h>main(){//声明字符型数组和指针变量char str[10];char *strip=str;//输入输出cout<<"str=";cin>>str; //用字符数组输入字符串cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;cout<<"strip=";cin>>strip; //用字符指针变量输入字符串cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;//利用指针变量改变其指向字符串的内容*(strip+2)='l';cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;//动态为字符型指针变量分配内存strip=new char(100);cout<<"strip=";cin>>strip; //用字符指针变量输入字符串cout<<"str="<<str<<endl;cout<<"strip="<<strip<<endl;}#include<iostream.h>main(){// 声明用于存放运动员号码的数组int h[]={1001,1002,1003,1004};// 声明用于存放运动员成绩的数组float x[]={12.3,13.1,11.9,12.1};//声明用于存放运动姓名的字符型指针数组char *p[]={"Wang hua","Zhang jian","Li wei","Hua ming"};//i,j,it是用做循环控制变量和临时变量int i,j,it;//ft 用做暂存变量float ft;//pt为字符型指针变量用做暂存指针变量char *pt;//用选择法对数组x进行排序,并相应调整数组h和p中的数据for (i=0;i<=3;i++)for (j=i+1;j<=3;j++)if (x[i]>=x[j]) {ft=x[i],x[i]=x[j],x[j]=ft;it=h[i],h[i]=h[j],h[j]=it;pt=p[i],p[i]=p[j],p[j]=pt;}//以下打印排序结果for (i=0;i<=3;i++)cout<<h[i]<<" ,"<<p[i]<<" ,"<<x[i]<<endl;}#include<iostream.h>main(){//声明指针数组char *colors[]={"Red","Blue","Yellow","Green"};//指向指针的指针变量char **pt;//通过指向指针的变量访问其指向的内容pt=colors;for (int i=0;i<=3;i++) {cout<<"pt="<<pt<<endl;cout<<"*pt="<<*pt<<endl;cout<<"**pt="<<**pt<<endl;pt++;}}#include<iostream.h>main(){//定义结构类型struct books{char title[20];char author[15];int pages;float price;} ;//声明结构变量struct books Zbk={"VC++ ","Zhang",295,35.5};books Wbk;//对结构变量的输出cout<<"Zbk:"<<endl;cout<<Zbk.title <<endl;cout<<Zbk.author<<endl;cout<<Zbk.pages<<endl;cout<<Zbk.price<<endl;cout<<"--------------------"<<endl;//对结构成员的运算Zbk.pages+=10;Zbk.price+=0.5;cout<<"Zbk.pages="<<Zbk.pages<<endl;cout<<"Zbk.price="<<Zbk.price<<endl;cout<<"--------------------"<<endl;//对结构变量的输入输出cout<<"Wbk.title =";cin>>Wbk.title;cout<<"Wbk.author=";cin>>Wbk.author;cout<<"Wbk.pages=";cin>>Wbk.pages;cout<<"Wbk.price=";cin>>Wbk.price;cout<<"Wbk:"<<endl;cout<<Wbk.title <<endl;cout<<Wbk.author<<endl;cout<<Wbk.pages<<endl;cout<<Wbk.price<<endl;cout<<"--------------------"<<endl;//结构变量之间的相互赋值books temp;temp=Wbk;cout<<"temp:"<<endl;cout<<temp.title<<endl;cout<<temp.author<<endl;cout<<temp.pages<<endl;cout<<temp.price<<endl;}#include<iostream.h>main(){int i;//定义结构类型struct student {int num;char name[10];float maths;float physics;float chemistry;double total;};//声明结构数组ststudent st[3];//从键盘上为结构数组输入值cout<<" num name maths physics chemistry "<<endl;for (i=0;i<3;i++){cout<<i+1<<" ";cin>>st[i].num;cin>>st[i].name;cin>>st[i].maths;cin>>st[i].physics;cin>>st[i].chemistry;}//计算每个学生的总成绩for (i=0;i<3;i++)st[i].total=st[i].maths+st[i].physics+st[i].chemistry;//输出结构数组各元素的值for (i=0;i<3;i++){cout<<"st["<<i<<"]: ";cout<<st[i].num<<'\t';cout<<st[i].name<<'\t';cout<<st[i].maths<<'\t';cout<<st[i].physics<<'\t';cout<<st[i].chemistry<<'\t';cout<<st[i].total<<endl;}}#include<iostream.h>main(){//定义结构类型struct human {char name[10];int sex;int age;};//声明结构变量和结构指针变量,并初始化struct human x={"WangPing",1,30},*p=NULL;//结构指针变量指向对象p=&x;//显示结构变量的值cout<<"="<<<<endl;cout<<"x.sex="<<x.sex<<endl;cout<<"x.age="<<x.age<<endl;//利用结构指针显示结构对象中的数据cout<<"(*p).name="<<(*p).name<<endl;cout<<"(*p).sex="<<(*p).sex<<endl;cout<<"(*p).age="<<(*p).age<<endl;cout<<"p->name="<<p->name<<endl;cout<<"p->sex="<<p->sex<<endl;cout<<"p->age="<<p->age<<endl;//通过结构指针为结构对象输入数据cout<<"name:";cin>>(*p).name;cout<<"sex:";cin>>(*p).sex;cout<<"age:";cin>>(*p).age;//显示结构变量的值cout<<"="<<<<endl;cout<<"x.sex="<<x.sex<<endl;cout<<"x.age="<<x.age<<endl;}include<iostream.h>main() {//定义结构类型struct human {char name[10];int sex;int age;};//声明结构变量和结构指针,并初始化struct human x={"WangPing",1,30},*p=&x;//利用结构指针显示结构中的数据cout<<"(*p).name="<<(*p).name<<endl;cout<<"(*p).sex="<<(*p).sex<<endl;cout<<"(*p).age="<<(*p).age<<endl;cout<<"-------------------------"<<endl;//利用new运算符为p分配内存p=new human;//从键盘上为p指向的结构对象赋值cout<<"p->name=";cin>>p->name;cout<<"p->sex=";cin>>p->sex;cout<<"p->age=";cin>>p->age;cout<<"-------------------------"<<endl;//显示p所指结构对象的值cout<<"p->name="<<p->name<<endl;cout<<"p->sex="<<p->sex<<endl;cout<<"p->age="<<p->age<<endl;cout<<"-------------------------"<<endl;//显示结构变量的值cout<<"="<<<<endl;cout<<"x.sex="<<x.sex<<endl;cout<<"x.age="<<x.age<<endl;//释放p指向的内存delete p;}#include<iostream.h>main(){//定义结构类型struct human {char name[10];int sex;int age;};//声明结构数组和结构指针变量,并初始化humanx[]={{"WeiPing",1,30},{"LiHua",1,25},{"LiuMin",0,23}},*p=NU LL;//用下标变量的输出结构数组的元素for (int i=0;i<3;i++){cout<<x[i].name<<'\t';cout<<x[i].sex<<'\t';cout<<x[i].age<<endl;}cout<<"----------------"<<endl;//用结构指针输出结构数组的元素for (p=x;p<=&x[2];p++){cout<<p->name<<'\t';cout<<p->sex<<'\t';cout<<p->age<<endl;}}#include<iostream.h>main(){//定义一个包含指针成员的结构类型struct test {char *str;int *ip;} x;//使用结构变量x中的整型指针ipx.ip=new int; //分配1个单元*(x.ip)=100;cout<<"x.ip:"<<x.ip<<'\t'<<*(x.ip)<<endl;cout<<"---------------"<<endl;delete x.ip;x.ip=new int[5]; //分配5个单元for(int i=0;i<5;i++)*(x.ip+i)=100+i;cout<<"x.ip:"<<endl;for(i=0;i<5;i++)cout<<x.ip+i<<'\t'<<(*(x.ip+i))<<endl;delete x.ip;cout<<"---------------"<<endl;//使用结构变量x中的字符型指针strx.str=new char('A'); //分配1个单元cout<<"x.str:"<<(*x.str)<<endl;cout<<"---------------"<<endl;delete x.str;x.str=new char[5]; //分配多个单元*x.str='G';*(x.str+1)='o';*(x.str+2)='o';*(x.str+3)='d';*(x.str+4)='\0';cout<<"x.str:"<<x.str<<endl;delete x.str;cout<<"---------------"<<endl;//在声明结构变量时初始化test y={"Very Good!",NULL};cout<<"y.str:"<<y.str<<endl;cout<<"y.ip:"<<y.ip<<endl;}#include<iostream.h> main(){//定义date结构struct date{int year;int month;int day;};//定义baby结构struct baby {int num;float weight;date birthday; // date为结构类型};//声明baby结构变量并初始化baby b1={10001,10,{2002,12,25}};//下列是baby结构变量b1的引用。
C语言头文件大全

标准C语言头文件ISOC标准定义的头文件(24项)<assert.h>验证程序断言<complex.h>?支持复数算术运算<ctype.h>?字符类型<errno.h>?出错码<fenv.h>?浮点环境<float.h>?浮点常量<inttypes.h>?整型格式转换<iso646.h>替代关系操作符宏<limits.h>?实现常量<locale.h>?局部类别<math.h>?数学常量<setjmp.h>非局部goto<signal.h>?信号<stdarg.h>?可变参数表<stdbool.h>?布尔类型和值<stddef.h>?标准定义<stdint.h>?整型<stdio.h>?标准I/O库<stdlib.h>?实用程序库函数<string.h>?字符串操作<tgmath.h>?通用类型数学宏<time.h>?时间和日期<wchar.h>?宽字符支持<wctype.h>?宽字符分类和映射支持POSIX标准定义的必须的头文件(26项)<dirent.h>?目录项<fcntl.h>?文件控制<fnmatch.h>?文件名匹配类型<glob.h>?路径名模式匹配类型<grp.h>?组文件<netdb.h>?网络数据库操作<pwd.h>口令文件<regex.h>?正则表达式<tar.h>?tar归档值<termios.h>?终端I/O <unistd.h>?符号常量<utime.h>?文件时间<wordexp.h>?字扩展类型<arpa/inet.h>?Internet定义<net/if.h>?套接字本地接口<netinet/in.h>Internet地址族<netinet/tcp.h>?传输控制协议 <sys/mman.h>?内存管理声明<sys/select.h>?select函数<sys/socket.h>?套接字接口<sys/stat.h>?文件状态<sys/times.h>?进程时间<sys/types.h>?基本系统数据类型<sys/un.h>?UNIX域套接字定义<sys/utsname.h>系统名<sys/wait.h>?进程控制POSIX标准定义的XSI扩展头文件(26项)<cpio.h>cpio归档值<dlfcn.h>?动态链接<fmtmsg.h>?消息显示结构<ftw.h>?文件树漫游<iconv.h>?代码集转换实用程序<langinfo.h>?语言信息常量<libgen.h>?模式匹配函数定义<monetary.h>?货币类型<ndbm.h>?数据库操作<nl_types.h>?消息类别<poll.h>?轮询函数<search.h>?搜索表<strings.h>?字符串操作<syslog.h>?系统出错日志记录<ucontext.h>?用户上下文<ulimit.h>?用户限制<utmpx.h>?用户帐户数据库<sys/ipc.h>IPC<sys/msg.h>?消息队列<sys/resource.h>资源操作<sys/sem.h>?信号量<sys/shm.h>?共享存储<sys/statvfs.h>?文件系统信息<sys/time.h>?时间类型<sys/timeb.h>?附加的时间<sys/uio.h>?矢量I/O操作POSIX标准定义的可选头文件(8项)<aio.h>?异步I/O <mqueue.h>?消息队列<pthread.h>?线程<sched.h>?执行调度<semaphore.h>信号量<spawn.h>?实时spawn接口<stropts.h>?XSISTREAMS接口<trace.h>?时间跟踪标准C++语言头文件(54个其中16个用于构建STL,3个为附加非必须)<algorithm>STL通用算法<bitset>STL位集容器<cassert>?用于在程序运行时执行断言<cctype>字符处理<cerrno>错误码<cfloat>?用于测试浮点类型属性<ciso646>?ISO646变体字符集<climits>?测试整数类型属性<clocale>本地化函数<cmath> 数学函数<complex>复数类<csetjmp>?执行非内部的goto语句<csignal>?信号<cstdarg>?访问参数数量变化的函数<cstddef>?用于定义实用的类型和宏<cstdio>输入/输出<cstdlib>杂项函数及内存分配<cstring>字符串<ctime> 时间<cwchar>宽字符处理及输入/输出<cwctype>宽字符分类<deque>STL双端队列容器<exception>异常处理类<fstream>文件流<functional>STL函数对象<iomanip>参数化输入/输出<ios>基本输入/输出支持<iosfwd>输入/输出前置声明<iostream>数据流输入/输出<istream>基本输入流<iterator>遍历序列的类<limits>各种数据类型最值常量<list>STL线性列表容器<locale>国际化支持<map>STL映射容器<memory>专用内存分配器<new>基本内存分配和释放? <numeric>通用的数字操作<ostream>基本输出流<queue> STL队列容器<set>STL集合容器<sstream>基于字符串的流<stack>STL堆栈容器<stdexcept>标准异常类<streambuf>iostream的缓冲区类<string>字符串类<strstream>?非内存字符序列的流类<typeinfo> 运行时类型标识<utility>STL通用模板类<valarray>?支持值数组的类和模版类<vector>STL动态数组容器标准C++附加的头文件(3个)非必须<hash_map> <hash_set> <slist>TheStandardC++libraryconsistsof51requiredheaders.Thisimplementationalsoincludesthreeaddit ionalheaders,<hash_map>,<hash_set>,and<slist>,notrequiredbytheC++Standard,foratotalof54he aders.Ofthese54headers,16constitutetheStandardTemplateLibrary,orSTL.Theseareindicatedbelo wwiththenotation<algorithm>--(STL)fordefiningnumeroustemplatesthatimplementusefulalgorithms<bitset> --fordefiningatemplateclassthatadministerssetsofbits<complex> --fordefiningatemplateclassthatsupportscomplexarithmetic<deque>--(STL)fordefiningatemplateclassthatimplementsadequecontainer<exception>--fordefiningseveralfunctionsthatcontrolexceptionhandling<fstream> --fordefiningseveraliostreamstemplateclassesthatmanipulateexteralfiles<functional>--(STL)fordefiningseveraltemplatesthathelpconstructpredicatesfor thetemplatesdefinedin<algorithm>and<numeric><hash_map>--(STL)fordefiningtemplateclassesthatimplementhashedassociativecontainers thatmapkeystovalues<hash_set>--(STL)fordefiningtemplateclassesthatimplementhashedassociativecontainers<iomanip> --fordeclaringseveraliostreamsmanipulatorsthattakeanargument<ios> --fordefiningthetemplateclassthatservesasthebaseformanyiostreamsclasses<iosfwd> --fordeclaringseveraliostreamstemplateclassesbeforetheyarenecessarilydefined<iostream> --fordeclaringtheiostreamsobjectsthatmanipulatethestandardstreams<istream> --fordefiningthetemplateclassthatperformsextractions<iterator>--(STL)fordefiningseveraltemplatesthathelpdefineandmanipulateiterators<limits> --fortestingnumerictypeproperties<list>--(STL)fordefiningatemplateclassthatimplementsadoublylinkedlistcontainer<locale> --fordefiningseveralclassesandtemplatesthatcontrollocale-specificbehavior,asintheiostreamsclasses<map>--(STL)fordefiningtemplateclassesthatimplementassociativecontainersthat mapkeystovalues<memory>--(STL)fordefiningseveraltemplatesthatallocateandfreestorageforvarious containerclasses<new> --fordeclaringseveralfunctionsthatallocateandfreestorage<numeric>--(STL)fordefiningseveraltemplatesthatimplementusefulnumericfunctions<ostream> --fordefiningthetemplateclassthatperformsinsertions<queue>--(STL)fordefiningatemplateclassthatimplementsaqueuecontainer<set>--(STL)fordefiningtemplateclassesthatimplementassociativecontainers<slist>--(STL)fordefiningatemplateclassthatimplementsasinglylinkedlistcontainer<sstream>--fordefiningseveraliostreamstemplateclassesthatmanipulatestringcontainers<stack>--(STL)fordefiningatemplateclassthatimplementsastackcontainer<stdexcept>--fordefiningseveralclassesusefulforreportingexceptions<streambuf>--fordefiningtemplateclassesthatbufferiostreamsoperations<string> --fordefiningatemplateclassthatimplementsastringcontainer<strstream>--fordefiningseveraliostreamsclassesthatmanipulatein-memorycharacter sequences<typeinfo> --fordefiningclasstype_info,theresultofthetypeidoperator<utility>--(STL)fordefiningseveraltemplatesofgeneralutility<valarray> --fordefiningseveralclassesandtemplateclassesthatsupportvalue-oriented arrays<vector>--(STL)fordefiningatemplateclassthatimplementsavectorcontainer新的C标准库<cassert> --forenforcingassertionswhenfunctionsexecute<cctype> --forclassifyingcharacters<cerrno> --fortestingerrorcodesreportedbylibraryfunctions<cfloat> --fortestingfloating-pointtypeproperties<ciso646> --forprogramminginISO646variantcharactersets<climits> --fortestingintegertypeproperties<clocale> --foradaptingtodifferentculturalconventions<cmath> --forcomputingcommonmathematicalfunctions<csetjmp> --forexecutingnonlocalgotostatements<csignal> --forcontrollingvariousexceptionalconditions<cstdarg> --foraccessingavaryingnumberofarguments<cstddef> --fordefiningseveralusefultypesandmacros<cstdio> --forperforminginputandoutput<cstdlib> --forperformingavarietyofoperations<cstring> --formanipulatingseveralkindsofstrings<ctime> --forconvertingbetweenvarioustimeanddateformats<cwchar> --formanipulatingwidestreamsandseveralkindsofstrings<cwctype> --forclassifyingwidecharacters旧的C标准库<assert.h> --forenforcingassertionswhenfunctionsexecute<ctype.h> --forclassifyingcharacters<errno.h> --fortestingerrorcodesreportedbylibraryfunctions<float.h> --fortestingfloating-pointtypeproperties<iso646.h> --forprogramminginISO646variantcharactersets<limits.h> --fortestingintegertypeproperties<locale.h> --foradaptingtodifferentculturalconventions<math.h> --forcomputingcommonmathematicalfunctions<setjmp.h> --forexecutingnonlocalgotostatements<signal.h> --forcontrollingvariousexceptionalconditions<stdarg.h> --foraccessingavaryingnumberofarguments<stddef.h> --fordefiningseveralusefultypesandmacros<stdio.h> --forperforminginputandoutput<stdlib.h> --forperformingavarietyofoperations<string.h> --formanipulatingseveralkindsofstrings<time.h> --forconvertingbetweenvarioustimeanddateformats<wchar.h> --formanipulatingwidestreamsandseveralkindsofstrings<wctype.h> --forclassifyingwidecharactersFinally,inthisimplementation,theStandardC++libraryalsoincludesseveralheadersforcompatibil itywithtraditionalC++libraries:<fstream.h>--fordefiningseveraliostreamstemplateclassesthatmanipulateexteralfiles<iomanip.h>--fordeclaringseveraliostreamsmanipulatorsthattakeanargument<iostream.h>--fordeclaringtheiostreamsobjectsthatmanipulatethestandardstreams<new.h> --fordeclaringseveralfunctionsthatallocateandfreestorage<stl.h> --fordeclaringseveraltemplateclassesthataidmigrationfromolderversions oftheStandardTemplateLibrary。
C语言代码大全

------------------------------------------------------------------------摘自宋鲁生程序设计大赛乘法口诀表#include <stdio.h>#include <conio.h>void main(void){int i,j,x,y;clrscr();printf("\n\n * * * 乘法口诀表* * * \n\n");x=9;y=5;for(i=1;i<=9;i++){gotoxy(x,y);printf("%2d ",i);x+=3;}x=7;y=6;for(i=1;i<=9;i++){gotoxy(x,y);printf("%2d ",i);y++;}x=9;y= 6;for(i=1;i<=9;i++){for(j=1;j<=9;j++){gotoxy(x,y);printf("%2d ",i*j);y++;}y-=9;x+=3;}printf("\n\n");}用一维数组统计学生成绩#include <stdio.h>void main(){char SelectKey,CreditMoney,DebitMoney;while(1){do{clrscr();puts("=========================");puts("| Please select key: |");puts("| 1. Quary |");puts("| 2. Credit |");puts("| 3. Debit |");puts("| 4. Return |");puts("=========================");SelectKey = getch();}while( SelectKey!='1' && SelectKey!='2' && SelectKey!='3' &&SelectKey!='4' );switch(SelectKey){case '1':clrscr();puts("================================");puts("| Your balance is $1000. |");puts("| Press any key to return... |");puts("================================");getch();break;case '2':do{clrscr();puts("==================================");puts("| Please select Credit money: |");puts("| 1. $50 |");puts("| 2. $100 |");puts("| 3. Return |");puts("==================================");CreditMoney = getch();}while( CreditMoney!='1' && CreditMoney!='2' && CreditMoney!='3' );switch(CreditMoney){case '1':clrscr();puts("=========================================");puts("| Your Credit money is $50,Thank you! |");puts("| Press any key to return... |");puts("=========================================");getch();break;case '2':clrscr();puts("==========================================");puts("| Your Credit money is $100,Thank you! |");puts("| Press any key to return... |");puts("==========================================");getch();break;case '3':break;}break;case '3':do{clrscr();puts("====================================");puts("| Please select Debit money: |");puts("| 1. $50 |");puts("| 2. $100 |");puts("| 3. $500 |");puts("| 4. $1000 |");puts("| 5. Return |");puts("====================================");DebitMoney = getch();}while( DebitMoney!='1' && DebitMoney!='2' && DebitMoney!='3' &&DebitMoney!='4' && DebitMoney!='5' );switch(DebitMoney){case '1':clrscr();puts("===========================================");puts("| Your Debit money is $50,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '2':clrscr();puts("===========================================");puts("| Your Debit money is $100,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '3':clrscr();puts("===========================================");puts("| Your Debit money is $500,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '4':clrscr();puts("===========================================");puts("| Your Debit money is $1000,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '5':break;}break;case '4':clrscr();puts("================================");puts("| Thank you for your using! |");puts("| Good bye! |");puts("================================");return;}}模拟ATM(自动柜员机)界面#include <stdio.h> void main(){int Password=0,Number=0,price=58,i=0;while( Password != 1234 ){if( i >= 3 )return;i++;puts("Please input Password: ");scanf("%d",&Password);}i=0;while( Number!=price ){do{puts("Please input a number between 1 and 100: ");scanf("%d",&Number);printf("Your input number is %d\n",Number);}while( !(Number>=1 && Number<=100) );if( Number >= 90 ){printf("Too Bigger! Press any key to try again!\n");}else if( Number >= 70 && Number < 90 ){printf("Bigger!\n");}else if( Number >= 1 && Number <= 30 ){printf("Too Small! Press any key to try again!\n");}else if( Number > 30 && Number <= 50 ){printf("Small! Press any key to try again!\n");}else{if( Number == price ){printf("OK! You are right! Bye Bye!\n");}else if( Number < price ){printf("Sorry,Only a little smaller! Press any key to try again!\n");}else if( Number > price ){printf(" Sorry, Only a little bigger! Press any key to try again!\n");}getch();}}用二维数组实现矩阵转置/* 用二维数组实现矩阵的转置*/#include <stdio.h>#define ROW 3#define COL 4main(){int matrixA[ROW][COL],matrixB[COL][ROW];int i,j; clrscr();printf("Enter elements of the matrixA,");printf("%d*%d:\n",ROW,COL);for( i=0; i<ROW; i++ ){for( j=0; j<COL; j++ ){scanf("%d",&matrixA[i][j]);}}for( i=0; i<ROW; i++ ){for( j=0; j<COL; j++ ){matrixB[j][i] = matrixA[i][j];}}printf("MatrixB,");printf("%d*%d:\n",COL,ROW);for( i=0; i<COL; i++ ){for( j=0; j<ROW; j++ ){printf("%8d",matrixB[i][j]);}printf("\n");}printf("\n Press Any Key to Quit... \n");getch();}求解二维数组的最大/最小元素#define MAXN 20int a[MAXN][MAXN];main(){int min, /* 存储最小值*/max; /* 存储最大值*/int row,col,n;clrscr();printf("Please input the order of the matrix:\n");/* 输入方阵的阶次*/ scanf("%d",&n);printf("Please input the elements of the matrix,\n from a[0][0] to a[%d][%d]:\n",n-1,n-1);for(row=0;row<n;row++)for(col=0;col<n;col++)scanf("%d",&a[row][col]);for(min=a[0][0],row=0;row<n;row++){/* 从每行选出最大数*/for(max=a[row][0],col=1;col<n;col++)/*从row行选出最大数*/if(max<a[row][col])max=a[row][col];if(min>max)/* 保存至row行的最小数*/min=max;}printf("The minimum of maximum number is %d\n",min);for(max=a[0][0],row=0;row<n;row++){/* 每行选出最小数*/for(min=a[row][0],col=1;col<n;col++)/* 从row行选出最小数*/ if(min>a[row][col])min=a[row][col];if(max<min)/*保存至row行的最大数*/max=min;}printf("The maximum of minimum numbers is %d\n",max);printf("\nPress any key to quit...\n");getch();}利用数组求前n个质数#define N 50main(){int primes[N];int pc,m,k; clrscr();printf("\n The first %d prime numbers are:\n",N);primes[0]=2;/*2是第一个质数*/pc =1;/*已有第一个质数*/m =3;/*被测试的数从3开始*/while(pc<N){/*调整m使它为下一个质数*/k=0;while(primes[k]*primes[k]<=m)if(m%primes[k]==0){/*m是合数*/m+=2;/*让m取下一个奇数*/k=1;/*不必用primes[0]=2去测试m,所以k从一开始*/}elsek++;/*继续用下一个质数去测试*/primes[pc++]=m;m+=2;/*除2外,其余质数均是奇数*/}/*输出primes[0]至primes[pc-1]*/for(k=0;k<pc;k++)printf("%4d",primes[k]);printf("\n\n Press any key to quit...\n ");getch();}编制万年历#include "stdio.h"long int f(int year,int month){/*f(年,月)=年-1,如月<3;否则,f(年,月)=年*/if(month<3) return year-1;else return year;} long int g(int month){/*g(月)=月+13,如月<3;否则,g(月)=月+1*/if(month<3) return month+13;else return month+1;} long int n(int year,int month,int day){/*N=1461*f(年、月)/4+153*g(月)/5+日*/return 1461L*f(year,month)/4+153L*g(month)/5+day;} int w(int year,int month,int day){/*w=(N-621049)%7(0<=w<7)*/return(int)((n(year,month,day)%7-621049L%7+7)%7);} int date[12][6][7];int day_tbl[ ][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};main(){int sw,leap,i,j,k,wd,day;int year;/*年*/char title[]="SUN MON TUE WED THU FRI SAT";clrscr();printf("Please input the year whose calendar you want to know: ");/*输入年*/scanf("%d%*c",&year);/*输入年份值和掠过值后的回车*/sw=w(year,1,1);leap=year%4==0&&year%100||year%400==0;/*判闰年*/for(i=0;i<12;i++)for(j=0;j<6;j++)for(k=0;k<7;k++)date[i][j][k]=0;/*日期表置0*/for(i=0;i<12;i++)/*一年十二个月*/for(wd=0,day=1;day<=day_tbl[leap][i];day++){/*将第i+1月的日期填入日期表*/date[i][wd][sw]=day;sw=++sw%7;/*每星期七天,以0至6计数*/if(sw==0) wd++;/*日期表每七天一行,星期天开始新的一行*/} printf("\n|==================The Calendar of Year %d=====================|\n|",year);for(i=0;i<6;i++){/*先测算第i+1月和第i+7月的最大星期数*/for(wd=0,k=0;k<7;k++)/*日期表的第六行有日期,则wd!=0*/wd+=date[i][5][k]+date[i+6][5][k];wd=wd?6:5;printf("%2d %s %2d %s |\n|",i+1,title,i+7,title);for(j=0;j<wd;j++){printf(" ");/*输出四个空白符*//*左栏为第i+1月,右栏为第i+7月*/for(k=0;k<7;k++)if(date[i][j][k])printf("%4d",date[i][j][k]);else printf(" ");printf(" ");/*输出十个空白符*/for(k=0;k<7;k++)if(date[i+6][j][k])printf("%4d",date[i+6][j][k]);else printf(" ");printf(" |\n|");}/*scanf("%*c");/*键入回车输出下一个月的日历*/}puts("=================================================================|") ;puts("\n Press any key to quit...");getch();}对数组元素排序rest(int a[], int n){int i,low,high,t; for(i=0,low=0,high=n-1;i<=high;) {if(a[i]>0){/*a[i]与a[high]交换,随之high减1*/t=a[i];a[i]=a[high];a[high]=t;high--;}else if(a[i]==0)i++; /* 掠过该元素*/else{/*a[i]与a[low]交换,随之low增1, i增1*/t=a[i];a[i]=a[low];a[low]=t;low++;i++;}}}int s[]={8,4,0,-1,6,0,-5};main(){int i;clrscr();printf("\n The arry before rest is:\n");for(i=0;i<sizeof(s)/sizeof(s[0]);i++)printf("%4d",s[i]);rest(s,sizeof(s)/sizeof(s[0]));printf("\n The arry after rest is:\n");for(i=0;i<sizeof(s)/sizeof(s[0]);i++)printf("%4d",s[i]);printf("\n Press any key to quit...\n");getch();}任意进制数的转换/* 函数trans将无符号整数n翻译成d(2<=d<=16)进制表示的字符串s */ #define M sizeof(unsigned int)*8int trans(unsigned n, int d, char s[]){static char digits[] ="0123456789ABCDEF"; /* 十六进制数字的字符*/char buf[M+1];int j, i = M;if(d<2||d>16){s[0]='\0'; /* 不合理的进制,置s为空字符串*/return 0; /* 不合理的进制,函数返回0 */}buf[i]='\0';do{buf[--i]=digits[n%d]; /*译出最低位,对应字符存入对应工作数组中*/n/=d;}while(n);/* 将译出在工作数组中的字符串复制到s */for(j=0;(s[j]=buf[i])!='\0';j++,i++);/* 其中控制条件可简写成s[j]=buf[i] */return j;}/* 主函数用于测试函数trans() */main(){unsigned int num = 253;int scale[]={2,3,10,16,1};char str[33];int i;clrscr();for(i=0;i<sizeof(scale)/sizeof(scale[0]);i++){if(trans(num,scale[i],str))printf("%5d = %s(%d)\n",num,str,scale[i]);elseprintf("%5d => (%d) Error! \n",num,scale[i]);}printf("\n Press any key to quit...\n");getch();}判断回文数/* 函数circle用于判断正整数n的d进制数表示形式是否是回文数*/ int circle(int n, int d){int s=0,m=n;while(m){s=s*d+m%d;m/=d;}return s==n;}/* main函数用于测试circle函数*/int num[]={232,27,851};int scale[]={2,10,16};main(){int i,j;clrscr();for(i=0;i<sizeof(num)/sizeof(num[0]);i++)for(j=0;j<sizeof(scale)/sizeof(scale[0]);j++)if(circle(num[i],scale[j]))printf("%d -> (%d) is a Circle Number!\n",num[i],scale[j]);elseprintf("%d -> (%d) is not a Circle Number!\n",num[i],scale[j]);printf("\n Press any key to quit...\n");getch();}求解钢材切割的最佳订单#include <stdio.h>#define N 20#define DELTA 2int bestlen;int bestsele[N];int sele[N];int n;int orderlen[N];int total;main(){int i;clrscr();printf("\n Please enter total length of the steel:\n");/* 输入钢材总长*/scanf("%d",&total);printf("\n Please enter number of order:\n"); /* 输入定单数*/ scanf("%d",&n);printf("\n Please enter the orders:\n"); /* 输入各定单*/for(i=0;i<n;i++)scanf("%d",&orderlen[i]);bestlen=0; /*最佳解用料的初值*/for(i=0;i<n;i++)sele[i]=bestsele[i]=0; /*置当前选择和最佳选择初值*/try(); /* 调用函数求解*/for(i=0;i<n;i++) /* 输出结果*/if(bestsele[i])printf("order %d length = %d\n",i+1,orderlen[i]);printf("\n Press any key to quit...");getch();}try(){int i,len;for(len=i=0;i<n;i++) /* 求当前选中的用料量*/if(sele[i])len+=orderlen[i]+DELTA;if(len-DELTA<=total) /* 注意最后一段可能不需要切割*/{if(bestlen < len){/* 找到一个更好的解*/bestlen = len;for(i=0;i<n;i++)bestsele[i]=sele[i];}for(i=0;i<n;i++) /* 对所有未选定单逐一作选中尝试循环*/if(!sele[i]){sele[i]=1; /* 做选中尝试*/try();sele[i]=0;}}}指向数组的指针main(){int x,y,z; /* 定义三个int型变量*/int *xp = &x, /* 定义指针变量xp,并赋值为x的地址,使xp指向x */ *yp = &y, /* 定义指针变量yp,并赋值为y的地址,使yp指向y */*zp = &z; /* 定义指针变量zp,并赋值为z的地址,使zp指向z */int t;printf("\nPlease input x,y,z:\n");scanf("%d%d%d",xp,yp,zp); /* 通过变量的指针,为变量输入值*/ if(*xp>*yp) /* 通过指向变量的指针引用变量的值*/{t=*xp; /* 通过指向变量的指针引用变量的值*/*xp=*yp;/* 通过指向变量x的指针xp,引用变量x的值*/*yp=t; /* 通过指向变量y的指针yp,引用变量y的值*/}if(*xp>*zp) /* 通过指向变量的指针,引用变量的值*/{t=*xp; /* 通过指向变量x的指针xp,引用变量x的值*/*xp=*zp;/* 通过指向变量x的指针xp,引用变量x的值*/*zp=t; /* 通过指向变量z的指针zp,引用变量z的值*/}if(*yp>*zp) /* 通过指向变量的指针,引用变量的值*/{t=*yp; /* 通过指向变量的指针,引用变量的值*/*yp=*zp;/* 通过指向变量y的指针yp,引用变量y的值*/*zp=t;/* 通过指向变量z的指针zp,引用变量z的值*/}printf("x = %d\ty = %d\tz = %d\n",x,y,z);printf("\nPress any key to quit...\n");getch();}阿拉伯数字转换为罗马数字#include <stdio.h>#define ROWS 4#define COLS 4int nums[ROWS][COLS]={{1000,1000,1000,1000},{900,500,400,100},{90,50,40,10},{9,5,4,1}};char *roms[ROWS][COLS]={{"m","m","m","m"}, {"cm","d","cd","c"},{"xc","l","xl","x"},{"ix","v","iv","i"}}; main(int argc,char *argv[ ]){int low,high;char roman[25]; if(argc<2){ printf("Usage:roman decimal_number\n");/*运行程序需带整数参数*/}high=low=atoi(argv[1]);/*将第一个参数转换成整数*/checknum(low);if(argc>2){/*带两个参数*/high=atoi(argv[2]);checknum(high);if(low>high){low=high;high=atoi(argv[1]);}}elselow=1;for(;low<=high;low++){to_roman(low,roman);printf("%d\t%s\n",low,roman);}} checknum(int val)/*检查参数合理性*/{if(val<1||val>9999){printf("The number must be in range 1..9999.\n");exit(0);}}to_roman(int decimal,char roman[ ])/*将整数转换成罗马数字表示*/ {int power,index;roman[0]='\0';for(power=0;power<ROWS;power++)for(index=0;index<COLS;index++)while(decimal>=nums[power][index]){strcat(roman,roms[power][index]);decimal-=nums[power][index];}}通讯录的输入输出#include <stdio.h>#define ZIPLEN 10#define PHONLEN 15/*struct addr类型定义*/ struct addr{char *name;/*姓名*/char *address;/*地址*/char zip[ZIPLEN];/*邮政编码*/char phone[PHONLEN];/*电话号码*/}; main()/*本主函数示意上述输入输出函数的用法*/{struct addr p[100];int i,j;clrscr();for(i=0;readaddr(p+i);i++);for(j=0;j<i;j++) writeaddr(p+j);puts("\n Press any key to quit...");getch();} /* 函数readaddr用于输入一个通信录函数*/int readaddr(struct addr *dpt){int len;char buf[120];/*输入字符串的缓冲区*/ printf("\nPlease input theName:\n");/*输入姓名*/if(scanf("%s",buf)==1){len=strlen(buf);dpt->name=(char *)malloc(len+1);/*申请存贮姓名的空间*/ strcpy(dpt->name,buf);}else return 0;/*Ctrl+Z结束输入*/printf("Please input the Address:\n");/*输入地址*/if(scanf("%s",buf)==1){len=strlen(buf);dpt->address=(char *)malloc(len+1);/*申请存贮地址的空间*/ strcpy(dpt->address,buf);}else{/*Ctrl+Z结束输入*/free(dpt->name);/*释放存贮姓名的空间*/return 0;}printf("Please input the Zip code:\n");/*输入邮编*/if(scanf("%s",buf)==1)strncpy(dpt->zip,buf,ZIPLEN-1);else{free(dpt->name);/*释放存贮姓名的空间*/free(dpt->address);/*释放存贮地址的空间*/return 0;/*Ctrl+Z结束输入*/}printf("Please input the Phone number:\n");/*输入电话号码*/ if(scanf("%s",buf)==1)strncpy(dpt->phone,buf,PHONLEN-1);else{free(dpt->name);free(dpt->address);return 0;/*Ctrl+Z结束输入*/}return 1;} /* 函数writeaddr用于输出通讯录*/int writeaddr(struct addr*dpt){printf("Name : %s\n", dpt->name);/*输出姓名*/printf("Address : %s\n", dpt->address);/*输出地址*/printf("Zip : %s\n", dpt->zip);/*输出邮编*/printf("Phone : %s\n\n", dpt->phone);/*输出电话号码*/}扑克牌的结构表示enum suits{CLUBS,DIAMONDS,HEARTS,SPADES}; struct card{enum suits suit;char value[3];};struct card deck[52];char cardval[][3]= {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};char suitsname[][9]={"CLUBS","DIAMONDS","HEARTS","SPADES"}; main() {int i,j;enum suits s;clrscr();for(i=0;i<=12;i++)for(s=CLUBS;s<=SPADES;s++){j=i*4+s;deck[j].suit=s;strcpy(deck[j].value,cardval[i]);}for(j=0;j<52;j++)printf("(%s%3s)%c",suitsname[deck[j].suit],deck[j].value,j%4==3?'\n':'\t');puts("\nPress any key to quit...");getch();}用“结构”统计学生成绩#include <stdio.h>#define N 200#define SCORES 5#define NUMLEN 10struct std_type{char no[NUMLEN];/*学号*/char *name;/*名字符串指针*/int scores[SCORES];/*五门功课的成绩*/};struct std_type students[N];int order[N];int total[N]; /*[函数]输入一个学生信息函数*/int readastu(struct std_type *spt){int len,j;char buf[120];/*输入字符串的缓冲区*/ printf("\nNumber : ");/*输入学号*/if(scanf("%s",buf)==1)strncpy(spt->no,buf,NUMLEN-1);elsereturn 0;/*Ctrl+Z结束输入*/printf("Name : ");/*输入姓名*/if(scanf("%s",buf)==1){len=strlen(buf);spt->name=(char *)malloc(len+1);/*申请存贮姓名的空间*/ strcpy(spt->name,buf);}else return 0;/*Ctrl+Z结束输入*/printf("Scores : ");/*输入成绩*/for(j=0;j<SCORES;j++)if(scanf("%d",spt->scores+j)!=1)break;if(j==0)/*一个成绩也未输入*/{free(spt->name);/*释放存贮姓名的空间*/return 0;}for(;j<SCORES;j++)/*少数未输入的成绩用0分代之*/ spt->scores[j]=0;return 1;} /*[函数]输出一个学生信息的函数*/int writeastu(struct std_type *spt){int i; printf("Number : %s\n",spt->no);/*输出学号*/printf("Name : %s\n",spt->name);/*输出姓名*/printf("Scores : ");/*输出成绩*/for(i=0;i<SCORES;i++)printf("%4d",spt->scores[i]);printf("\n\n");} main(){int n,i,j,t; clrscr();for(n=0;readastu(students+n);n++);/*采用冒泡法对学生信息数组排序*/for(i=0;i<n;i++){order[i]=i;/*预置第i个输入的学生*/for(t=0,j=0;j<SCORES;j++)/*求第i个学生的总分*/t+=students[i].scores[j];total[i]=t;}/*冒泡排序*/for(i=0;i<n-1;i++)/*共扫视n-1遍*/for(j=0;j<n-1-i;j++)if(total[order[j]]<total[order[j+1]]){/*交换名次*/t=order[j];order[j]=order[j+1];order[j+1]=t;}for(j=0;j<n;j++)/*输出*/writeastu(students+order[j]);printf("\n Press any key to quit...\n");getch();}报数游戏#include <stdio.h>struct ele{int no;struct ele *link;}main(){int n,m,i;struct ele *h,*u,*p;clrscr();printf("Please input n&m:\n");scanf("%d%d",&n,&m);/*输入n和m*/h=u=(struct ele *)malloc(sizeof(struct ele));/*形成首表元*/ h->no=1;for(i=2;i<=n;i++)/*形成其余的n-1个表元*/{u->link=(struct ele *)malloc(sizeof(struct ele));u=u->link;u->no=i;/*第i个表元置编号i*/}u->link=h;/*末表元后继首表元,形成环*/puts("\nThe numbers of who will quit the cycle in turn are:"); while(n){for(i=1;i<m;i++)/*掠过m-1个表元*/u=u->link;p=u->link;/*p指向第m个表元*/u->link=p->link;/*第m个表元从环中脱钩*/printf("%4d",p->no);free(p);/*释放第m个表元占用的空间*/n--;}printf("\n\n Press any key to quit...\n");getch();}学生成绩管理程序/*学生成绩管理程序编制一个统计学生考试分数的管理程序。
经典C语言源代码.docx

经典 C 语言源代码1、(1)某年某月某日是星期几#include<stdio.h>int main(){int year, month, day;while (scanf_s("%d%d%d", &year, &month, &day) != EOF){if (month == 1 || month == 2)// 判断month 是否为1 或2 {year--;month += 12;}int c = year / 100;int y = year - c * 100;int week = (c / 4) - 2 * c + (y + y / 4) + (13 * (month + 1) / 5) day - 1;while (week<0) { week += 7; }week %= 7;switch (week){case 1:printf("Monday\n"); break;case 2:printf("Tuesday\n"); break;case 3:printf("Wednesday\n"); break;case 4:printf("Thursday\n"); break;case 5:printf("Friday\n"); break;case 6:printf("Saturday\n"); break;case 0:printf("Sunday\n"); break;}}return 0;}1、(2)某年某月某日是第几天(一维数组)#include "stdio.h" void main() {int i, flag, year, month, day, dayth;int month_day[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };printf(" 请输入年/月/日:\n");scanf_s("%d/%d/%d", &year, &month, &day);dayth = day;flag = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);if (flag)month_day[2] = 29;for (i = 1; i < month; i++)dayth = dayth + month_day[i];Prin tf("%d∕%d∕%d 是第%d 天\n", year, mon th, day, dayth);}2、30 个数中找最小的数及其位置#include "stdio.h"# define SIZE 30void main() {int i;float data[SIZE];int min;Printf("请输入%d个浮点数:∖n",SIZE);for (i = 0; i < SIZE; i++) {//scan f_s("%f", & data[i]); data[i] = rand() % 30 + 1;Printf("%f、", data[i]);}min = 0;for (i = 1; i < SIZE; i++) { if(data[i] < data[min])min = i;}Printf("最小值是%5.2f位置是%5d∖n", data[min], min); }3、30 个数从小到大排序(1)#include "stdio.h"# define SIZE 30void main() {int i,j;float data[SIZE],temP;int min;Printf("请输入%d个整型数:∖n",SIZE);for (i = 0; i < SIZE; i++) {scanf_s("%f", &data[i]);}for (i = 0; i < SIZE; i++) { min = i;for (j = i + 1; j < SIZE; j++)if (data[j] < data[min])temp = data[min];min = j;data[min] = data[i]; data[i] = temp;}printf("\n 排序后的结果是:\n");for (i = 0; i < SIZE; i++) printf("%5.2f", data[i]);}(2)模块化程序(数组名作为函数参数) #include "stdio.h"# define SIZE 5void accept_array(float a[], int size); void sort(float a[], int size); void show_array(float a[], int size);void main() {float score[SIZE]; accept_array(score, SIZE);printf(" 排序前:"); show_array(score, SIZE);sort(score, SIZE);printf(" 排序后:"); show_array(score, SIZE); }void accept_array(float a[], int size) {int i;printf(" 请输入%d 个分数:", size);for (i = 0; i < size; i++) scanf_s("%f", &a[i]);}void show_array(float a[], int size) {int i;for (i = 0; i < size; i++)printf(" %5.2f", a[i]);printf("\n");}void sort(float a[],int size) {int i, min, j;float temp;for (i = 0; i < SIZE; i++) {min = i;for (j = i + 1; j < SIZE; j++)if (a[j] < a[min])min = j;}temp = a[min]; a[min] = a[i]; a[i] = temp;}}4、( 1)指针加减:#include "stdio.h"#define SIZE 10 void main() {int a[SIZE] = { 1,2,3,4,5,6,7,8,9,10 }; int *pa, i;pa = &a[0];//pa=a; printf("\n");for (i = 0; i < SIZE; i++) { printf(" %d", *pa);//printf(" %d", *(pa+1)); pa++;(2)指针比较:#include "stdio.h"#define SIZE 10void main() {int a[SIZE] = { 1,2,3,4,5,6,7,8,9,10 };int *pa, i;int *qa;pa = qa = &a[0];printf(" 请输入%d 整型数:",SIZE); for (; pa < qa + SIZE;pa++) scanf_s("%d", pa);for (pa--; qa <= pa; pa--)printf(" %d", *pa);}5、两字符串相连:#include "stdio.h"#include "string.h"void str_cat(char str1[], char str2[]); void main() {int i, j;char str1[160];char str2[80];printf(" 请输入第一个字符串:"); gets(str1);printf(" 请输入第二个字符串:"); gets(str2);str_cat(str1, str2);puts(str1);}void str_cat(char str1[], char str2[]) { int i, j;i = 0;while (str1[i] != '\0')i++;j = 0;while (str2[j] != '\0') {str1[i] = str2[j]; i++; j++;}str1[i] = '\0';6、二维数组( a,b 转置) #include "stdio.h" void main() {int i, j, b[2][3];int a[3][2] = { {1,2},{3,4},{5,6} };for (i = 0; i < 2; i++) {}for (j = 0; j < 3; j++)b[i][j] = a[j][i];}printf("\na:\n");for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) printf("%5d", a[i][j]);printf("\n");}printf("\nb:\n");for(i = 0; i < 2; i++) { for (j = 0; j < 3; j++) printf("%5d", b[i][j]);printf("\n");}7、输入一个二维数组并输出(指针)#include "stdio.h"void main() {int x[2][3];int i, j;for (i = 0; i < 2; i++)for (j = 0; j < 3; j++)scanf_s("%d", *(x + i) + j); putchar('\n');for (i = 0; i < 2; i++){for (j = 0; j < 3; j++)printf("%d ", *(*(x + i) + j));putchar('\n');}}8、冒泡法排序一个数组#include "stdio.h"#define size 10 void maopao(int a[]); void main() { int a[10];int i;printf(" 请输入10 个整数:\n"); for (i = 0; i < 10; i++) scanf_s("%d", &a[i]); maopao(a);}void maopao(int a[]) {int i, j, temp;for (i = 0; i < 9; i++) {// 进行9 轮排序for (j = 0; j < 9 - i; j++)// 每轮进行9-i 次交换{if (a[j] > a[j + 1]){ temp = a[j];a[j] = a[j + 1];// 大的沉底,小的上浮a[j + 1] = temp;}}}printf(" 排序结果:\n"); for (i = 0; i < 10; i++) printf("%4d", a[i]); }9、两数组A,B,要求A<B,如A :4,7,9B :1,3,5,8,9变换后A :1,3,5B :4,7,8,9,9#include <stdio.h>VOid ReArranger(int* A, int* B, int m, int n) //A 和B是各有m 个和n 个整数的非降序数组,本算法将B 数组元素逐个插入到A 中,使A 中各元素均不大于B 中各元素,且两数组仍保持非降序排列。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
int main(void)
{
if(isalnum('a')) printf("It's True"); // 显示 It's True
if(isalnum(4)) printf("It's True"); // 显示 ''
if(isalnum('4')) printf("It's True"); // 显示 It's True
C/C++头文件一览 C、传统 C++
#include <assert.h> 使用断言
//设定插入点
assert()宏是用于保证满足某个特定条件,用法是: assert(表达式); 如果表达式的值为假,整个程序将退出,并输出一条错误信息。如果表达式的值为真则继续执行后面的语句。
使用这个宏前需要包含头文件 assert.h 例如
return 0;
} isdigit()函数的作用是判断一个字符是否是字符类的数字:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
if(isdigit('4')) printf("It's True"); // 显示 It's True
if(isdigit(4)) printf("It's True"); // 显示 ''
if(isdigit('a')) printf("It's True"); // 显示 ''
符(\t))
isupper 判断一个字符是否是大写字母
isxdigit 判断一个字符是否是一个十六进制的数字
tolower 将大些字符转换为小写
toupper 将小写字符转换为大写
isalnum()函数的作用是判断一个字符是否是字符类的数字或者字母:
#include <stdio.h>
#include <ctype.h>
isgraph 判断一个字符是否是可打印字符(ascii 码 33-126 之间的字符)
islower 判断一个字符是否是小写字母
isprint 判断一个字符是否是包含空格在内的可打印字符(ascii 码 32-126 之间的字符)
ispunct 判断一个字符是否是除空格,字母,数字外的标点符号
isspace 判断一个字符是空白字符(空格,换行符(\n),走纸符(\f),回车符(\r),垂直制表符(\v),水平制表
return 0;
} isalpha()函数的作用是判断一个字符是否是字母:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
if(isalpha('a')) printf("It's True"); // 显示 It's True
if(isalpha(4)) printf("It's True"); // 显示 ''
#include <ctype.h>
//字符处理
isalnum 判断一个字符是否是字符类的数字或者字母
isalpha 判断一个字符是否是字母
isblank 判断一个字符是空白字符(空格和水平制表符 Tab)
iscntrl 判断一个控制符(ascii 码 0-31 之间的字符)
isdigit 判断一个字符是否是字符类的数字
if(isblank('\n')) // 换行 printf("It's True"); // 显示 ''
if(isblank('\r')) // 回车 printf("It's True"); // 显示 ''
if(isspace(' ')) // 空格 printf("It's True"); // 显示 It's True
#include <stdio.h>
#include <assert.h>
void main()
{
float a,b;
scan("%f %f",&a,&b);
assert(b!=0);
printf("%f\n",a/b);
} 以上的程序要计算 A/B 的值,因此要求 b!=0,所以在程序中使用了 assert()用于确保 b!=0,如果 b==0, 则程序会退出。
return 0;
} iscntrl()函数的作用是判断一个控制符(ascii 码 0-31 之间的字符):
#include <stdio.h>
#include <ctype.h>
int main(void)
{ if(isblank(' ')) // 空格 printf("It's True"); // 显示 ''
if(isalpha('4')) printf("It's True"); // 显示 ''
1
return 0;
} isblank()函数的作用是判断一个字符是空白字符(空格和水平制表符 Tab),isspace()函数和 isblank()函数 类似,但是还包含空格,换行符(\n),走纸符(\f),回车符(\r),垂直制表符(\v),水平制表符(\t):
if(isblank('\t')) // Tab printf("It's True"); // 显示 It's True
if(isblank('\n')) // 换行 printf("It's True"); // 显示 It's True
if(isblank('\r')) // 回车 printf("It's True"); // 显示 It's True
if(isspace('\t')) // Tab printf("It's True"); // 显示 It's True
if(isspace('\n')) // 换行 printf("It's True"); // 显示 It's True
if(isspace('\r')) // 回车 printf("It's True"); // 显示 It's True
#include <stdio.h>
#include <ctype.h>
int main(void)
{ if(isblank(' ')) // 空格 pr); // 显示 It's True
if(isblank('\t')) // Tab printf("It's True"); // 显示 It's True