c++经典代码大全
C语言程序大全
C语言程序大全一、概述C语言是一种十分常用的编程语言,广泛应用于多个领域,包括操作系统、嵌入式系统、游戏开发等。
本文将为您提供一份C语言程序大全,涵盖了常见的C语言程序示例,帮助您更好地理解和运用C语言。
二、基本语法1. Hello, World! 程序示例```c#include <stdio.h>int main() {printf("Hello, World!\n");return 0;}```以上代码是C语言的经典入门示例,它会在控制台输出"Hello, World!"。
通过此示例,您可以了解到C语言的基本语法,如#include 指令、main函数等。
2. 变量和数据类型示例```c#include <stdio.h>int main() {int num1 = 10;float num2 = 3.14;char ch = 'A';printf("num1 = %d\n", num1);printf("num2 = %f\n", num2);printf("ch = %c\n", ch);return 0;}```以上代码展示了如何声明和初始化变量,并输出它们的值。
通过此示例,您可以学习到C语言的基本数据类型,如整型、浮点型、字符型等。
3. 条件语句示例```c#include <stdio.h>int main() {int num = 10;if (num > 0) {printf("num is positive.\n");} else if (num < 0) {printf("num is negative.\n");} else {printf("num is zero.\n");}return 0;}```以上代码展示了如何使用条件语句来进行判断。
C经典程序代码大全
//根据半径计算圆的周长和面积#include <iostream.h>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="; //显示字符串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(){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;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<<" 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*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类型变量相互赋值//布尔变量超界处理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>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);//计算显示(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 {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(){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;elsecout<<"Your grade is a E."<<endl;#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;break;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++) {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<<"]=";}//直接显示数组元素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<<"]=";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<<"]=";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++){。
经典C语言编程100例精编版
经典C语言编程100例(1-30)【程序1】题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。
组成所有的排列后再去掉不满足条件的排列。
2.程序源代码:main(){int i,j,k;printf("\n");for(i=1;i<5;i++) /*以下为三重循环*/for(j=1;j<5;j++)for (k=1;k<5;k++){if (i!=k&&i!=j&&j!=k) /*确保i、j、k三位互不相同*/printf("%d,%d,%d\n",i,j,k);}}============================================================== 【程序2】题目:企业发放的奖金根据利润提成。
利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?1.程序分析:请利用数轴来分界,定位。
注意定义时需把奖金定义成长整型。
2.程序源代码:main(){long int i;int bonus1,bonus2,bonus4,bonus6,bonus10,bonus;scanf("%ld",&i);bonus1=100000*0.1;bonus2=bonus1+100000*0.75;bonus4=bonus2+200000*0.5;bonus6=bonus4+200000*0.3;bonus10=bonus6+400000*0.15;if(i<=100000)bonus=i*0.1;else if(i<=200000)bonus=bonus1+(i-100000)*0.075;else if(i<=400000)bonus=bonus2+(i-200000)*0.05;else if(i<=600000)bonus=bonus4+(i-400000)*0.03;else if(i<=1000000)bonus=bonus6+(i-600000)*0.015;elsebonus=bonus10+(i-1000000)*0.01;printf("bonus=%d",bonus);}============================================================== 【程序3】题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?1.程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足如下条件,即是结果。
(完整版)c语言初学必背代码
//1.成绩判断#include <stdio.h>int main(){//成绩int score;printf("请输入你的成绩:\n");scanf("%d", &score);//判断if(score >=0 && score < 60){printf("不及格\n");}else if(60 <= score && score < 80){printf("中等\n");}else if(80 <= score && score < 100){printf("优秀\n");}else{printf("输入错误!\n");}}//2.计算1到100的和#include <stdio.h>int main(){int sum = 0;//存结果变量int i;for(i=1;i <= 100;i++){sum = sum + i;}printf("sum=%d\n", sum);}//3.最大公约数#include <stdio.h>//求m,n的最大公约数int main(){int m, n;int i, k;printf("请输入两个数:");scanf("%d %d", &m, &n);//三元运算符找较小的那个k = m < n ? m : n;//从较小的那个数倒着往前找for(i=k; i>=1; i--){//这是公约数if((m % i == 0) && (n % i ==0)){printf("最大公约数是%d\n", i);break;//跳出for循环}}}//4.最小公倍数#include <stdio.h>//求m,n的最小公倍数int main(){int m, n;int max, min;//m,n中较大,较小的那个int k;//max, 2*max, 3*max, .....printf("请输入两个数:");scanf("%d %d", &m, &n);//也可以交换m,n,保证m小n大max = m > n ? m : n;min = m < n ? m : n;k = max;//从max开始while(k % min != 0){k += max;//每次倍增}printf("最小公倍数是%d\n", k); }//5.金字塔#include <stdio.h>//金字塔int main(){int i;//外层int j;//内层for(i=1;i<=10;i++){//当前是在第i行//先补空格10-i个for(j=1;j<=10-i;j++){printf(" ");}//再打2i-1个*for(j=1;j<=2*i-1;j++){printf("*");}printf("\n");}}//6.九九乘法表#include <stdio.h>//打印九九乘法表int main(){int i,j;for(i=1;i<=9;i++)//外层一定是9行{for(j=1; j<=i; j++)//内层第几行走几遍{printf("%d*%d=%d ", i, j, i*j);}printf("\n");}}//7.百钱买百鸡#include <stdio.h>/**百钱买百鸡,类似1,2,5凑100银币问题*/int main2(){int i,j;//公鸡,母鸡个数for(i=0; i<=20; i++)//公鸡{for(j=0; j<=33; j++)//母鸡{if( (15*i + 9*j + (100-i-j)) == 300){printf("公鸡%d,母鸡%d,小鸡%d\n", i, j, 100-i-j);}}}}//1,2,5凑100银币问题int main3(){int count = 0;//情况数int i,j;//5分个数,2分个数for(i=0; i<=20; i++)//5分个数{for(j=0; j<=50; j++)//2分个数{if( ( 5*i + 2*j ) <= 100 ){count++;printf("%d: 5分%d个,2分%d 个,1分%d个\n", count, i, j, 100-5*i-2*j);}}}}//8.一维数组的最大值、最小值、平均值#include <stdio.h>#define N 10//宏定义常量int main(){int i;//下标索引int max, min;double sum = 0;//累加和int a[N] = {58, 58, 96, 100, 25, 55, 66, 88, 99, 77};max = a[0];//假设第一个最大min = a[0];//假设第一个最小for(i=1; i<N; i++){if(a[i] > max)//比最大值还大max = a[i];//你才是最大if(a[i] < min)//比最小值还小min = a[i];//你才是最小sum += a[i];}printf("max=%d, min=%d\n", max, min);printf("average = %.2lf\n", sum/N);}//9.二维数组的最大值、最小值、平均值#include <stdio.h>int main(){int i; //第几行int j; //第几列int a[3][4] = { {1,2,3,4}, {5,-6,7,8}, {9,19,39,0}};int max = a[0][0];//假设你最大int min = a[0][0];//假设你最小double average;//平均值double sum = 0; //总和for(i=0; i<3; i++)//必定3行{for(j=0; j<4; j++)//必定4列{printf("%5d ", a[i][j]);sum += a[i][j];if(a[i][j] > max)max = a[i][j];if(a[i][j] < min)min = a[i][j];}printf("\n");}average = sum / (3*4);printf("max=%d, min=%d, avg=%.2lf\n", max, min, average);}//10.二维数组转置#include <stdio.h>//二维数组转置:行变列,列变行int main(){int i; //第几行int j; //第几列int a[3][4] = { {1,2,3,4}, {5,-6,7,8}, {9,19,39,0}};int b[4][3];for(i=0; i<3; i++){for(j=0; j<4; j++){printf("%5d", a[i][j]);}printf("\n");}//矩阵转置for(i=0; i<3; i++){for(j=0; j<4; j++){b[j][i] = a[i][j];}}for(i=0; i<4; i++){for(j=0; j<3; j++){printf("%5d", b[i][j]);}printf("\n");}}//11.冒泡排序#include <stdio.h>#define N 10//宏定义常量int main(){int i;//下标索引int j;int tmp;//临时交换用int a[N] = {58, 58, 96, 100, 25, 55, 66, 88, 99, 77};//外层循环一定是N-1for(i=0; i<N-1; i++){//两两交换,大的往后走for(j=0; j<N-i-1; j++){//交换if(a[j] > a[j+1]){tmp = a[j];a[j] = a[j+1];a[j+1] = tmp;}}}for(i=0; i<N; i++){printf("%d ", a[i]);;}printf("\n");}//12.结构冒泡排序#include <stdio.h>//结构定义,用户自定义类型typedef struct student{char sno[20];//学号char name[20];//姓名int age;//年龄char gender;//性别char tel[20];//电话};int main(){int i;int j;double sum = 0;struct student tmp;//两两交换临时用;//结构数组struct student team[5];for(i=0; i<5; i++){printf("请输入第%d个队员的信息:\n", i+1);scanf("%s %s %d %c %s", team[i].sno, team[i].name, &team[i].age, &team[i].gender, team[i].tel);}//按年龄冒泡排序for(i=0; i<5; i++){for(j=0; j<5-i-1; j++){//两两交换if(team[j].age > team[j+1].age){tmp = team[j];team[j] = team[j+1];team[j+1] = tmp;}}}//取值printf("%-12s %-10s %-5s %-5s %-15s\n", "学号", "姓名", "年龄", "性别", "电话");for(i=0; i<5; i++){printf("%-12s %-10s %-5d %-5c %-15s\n", team[i].sno, team[i].name, team[i].age, team[i].gender, team[i].tel);}}//13.结构数组找年龄最大值#include <stdio.h>//结构定义,用户自定义类型typedef struct student{char sno[20];//学号char name[20];//姓名int age;//年龄char gender;//性别char tel[20];//电话};int main(){int i;struct student tmp;//找最大临时用//结构数组struct student team[5];for(i=0; i<5; i++){printf("请输入第%d个队员的信息:\n", i+1);scanf("%s %s %d %c %s", team[i].sno, team[i].name, &team[i].age, &team[i].gender, team[i].tel);}//取值printf("%-12s %-10s %-5s %-5s %-15s\n ", "学号", "姓名", "年龄", "性别", "电话");for(i=0; i<5; i++){printf("%-12s %-10s %-5d %-5c %-15s\ n", team[i].sno, team[i].name, team[i].age, team[i].gender, team[i].tel);}//找学号最大的那一个tmp = team[0];for(i=1; i<5; i++){if(strcmp(team[i].sno,tmp.sno) >0 ){tmp = team[i];}}printf("学号最大的队员如下:\n");printf("%-12s %-10s %-5d %-5c %-15s\ n", tmp.sno, , tmp.age, tmp.gender, tmp.tel);}//14.文件读写#include <stdio.h>#include <stdlib.h>//结构定义,用户自定义类型typedef struct student{char sno[20];//学号char name[20];//姓名int age;//年龄char gender;//性别char tel[20];//电话};//文件读写int main(){struct student * s, * p1;//个数未知FILE * fp;int i, n = 0;char buf[1024];//fgets缓冲区//打开文件fp = fopen("e:\\test.txt", "r");while(fgets(buf, 1024, fp) != NULL)n++;fclose(fp);//指向一个可以存储n个student结构的内存空间s = (struct student *)malloc(sizeof(struct student) * n);p1 = s;//不要动头位置s的值//打开文件fp = fopen("e:\\test.txt", "r");for(i=0; i<n; i++){//从文件中读入一行fscanf(fp, "%s %s %d %c %s", p1->sno, p1->name, &p1->age, &p1->gender, p1->tel);p1++;}fclose(fp);p1 = s;for(i=0; i<3; i++){printf("%s %s %d %c %s\n", p1->sno, p1->name, p1->age, p1->gender, p1->tel);}free(s);}//15.输入三角形三边长计算周长和面积#include<stdio.h>#include<math.h>int main(){double area,perimeter,s,a,b,c;printf("请输入三边长a b c:");scanf("%lf%lf%lf",&a,&b,&c);if((a+b>c) && (a+c>b) && (b+c>a)){s=(a+b+c)/2;area=sqrt(s*(s-a)*(s-b)*(s-c));perimeter=a+b+c;printf("area=%.2f,perimeter=%.2f\ n",area,perimeter);}else{printf("三边长无法构成三角形。
CPP经典代码大全
#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>#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 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(){//声明字符型数组和指针变量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(){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语言源代码.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 中各元素,且两数组仍保持非降序排列。
(完整版)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){}break; case '3':do{ 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;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=0; i++;puts("Please input Password: "); scanf("%d",&Password);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 ){}else{printf("Small! Press any key to try again!\n");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语言经典源码程序
【百条C语言经典源码程序】~~【程序1】题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。
组成所有的排列后再去掉不满足条件的排列。
2.程序源代码:main(){int i,j,k;printf("\n");for(i=1;i<5;i++)/*以下为三重循环*/for(j=1;j<5;j++)for (k=1;k<5;k++){if (i!=k&&i!=j&&j!=k) /*确保i、j、k三位互不相同*/printf("%d,%d,%d\n",i,j,k);}}【程序3】题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?1.程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足如下条件,即是结果。
请看具体分析:2.程序源代码:#include "math.h"main(){long int i,x,y,z;for (i=1;i<100000;i++){ x=sqrt(i+100); /*x为加上100后开方后的结果*/y=sqrt(i+268); /*y为再加上168后开方后的结果*/if(x*x==i+100&&y*y==i+268)/*如果一个数的平方根的平方等于该数,这说明此数是完全平方数*/printf("\n%ld\n",i);}}====================================================== ========【程序4】题目:输入某年某月某日,判断这一天是这一年的第几天?1.程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
C语言代码大全(可编辑修改word版)
乘法口诀表 #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++) {
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)
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' &&
经典C语言源代码
经典C语言源代码1、(1)某年某月某日是星期几#include<stdio.h>intmain(){intyear,month,day;{if(month==1||month==2)//判断month是否为1或2{ year--;month+=12;}intc=year/100;inty=year-c*100;intweek=(c/4)-2*c+(y+y/4)+(13*(month+1)/5)+day-1;while(week<0){week+=7;}week%=7;switch(week){}}return0;}1、(2)某年某月某日是第几天(一维数组)voidmain(){inti,flag,year,month,day,dayth;intmonth_day[]={0,31,28,31,30,31,30,31,31,30,31,30,31};请输入年/月/日: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];是第%4天}2、30个数中找最小的数及其位置#defineSIZE30voidmain(){inti;floatdata[SIZE];intmin;请输入%d个浮点数:for(i=0;i<SIZE;i++){data[i]=rand()%30+1;、}min=0;for(i=1;i<SIZE;i++){if(data[i]<data[min])min=i;最小值是%5.2f,位置是}3、30个数从小到大排序(1)#defineSIZE30voidmain(){inti,j;floatdata[SIZE],temp;intmin;请输入%d个整型数:for(i=0;i<SIZE;i++){}for(i=0;i<SIZE;i++){min=i;for(j=i+1;j<SIZE;j++)if(data[j]<data[min])temp=data[min];data[min]=data[i];data[i]=temp;}排序后的结果是:for(i=0;i<SIZE;i++)min=j;}(2)模块化程序(数组名作为函数参数)#defineSIZE5voidaccept_array(floata[],intsize);voidsort(floata[],intsize); voidshow_array(floata[],intsize);voidmain(){floatscore[SIZE];accept_array(score,SIZE);排序前:show_array(score,SIZE);sort(score,SIZE);排序后:show_array(score,SIZE);}voidaccept_array(floata[],intsize){inti;请输入%d个分数:for(i=0;i<size;i++)}voidshow_array(floata[],intsize){inti;for(i=0;i<size;i++)}voidsort(floata[],intsize){inti,min,j;floattemp;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)指针加减:#defineSIZE10voidmain(){inta[SIZE]={1,2,3,4,5,6,7,8,9,10};int*pa,i;pa=&a[0];//pa=a;for(i=0;i<SIZE;i++){pa++;(2)指针比较:#defineSIZE10voidmain(){inta[SIZE]={1,2,3,4,5,6,7,8,9,10};int*pa,i;int*qa;pa=qa=&a[0];请输入%d整型数:for(;pa<qa+SIZE;pa++)for(pa--;qa<=pa;pa--)}5、两字符串相连:voidstr_cat(charstr1[],charstr2[]);voidmain(){inti,j;charstr1[160];charstr2[80];请输入第一个字符串:gets(str1);请输入第二个字符串:gets(str2);str_cat(str1,str2);puts(str1);}voidstr_cat(charstr1[],charstr2[]){ inti,j;i=0;i++;j=0;str1[i]=str2[j];i++;j++;}}6、二维数组(a,b转置)voidmain(){inti,j,b[2][3];inta[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];}for(i=0;i<3;i++){for(j=0;j<2;j++)}for(i=0;i<2;i++){for(j=0;j<3;j++)}7、输入一个二维数组并输出(指针)voidmain(){intx[2][3];inti,j;for(i=0;i<2;i++)for(j=0;j<3;j++)putchar('');for(i=0;i<2;i++){for(j=0;j<3;j++)putchar('');}}8、冒泡法排序一个数组#definesize10voidmaopao(inta[]);voidmain(){inta[10];inti;请输入10个整数:for(i=0;i<10;i++)maopao(a);}voidmaopao(inta[]){inti,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;排序结果:for(i=0;i<10;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>voidReArranger(int*A,int*B,intm,intn)//A和B是各有m个和n个整数的非降序数组,本算法将B数组元素逐个插入到A中,使A中各元素均不大于B中各元素,且两数组仍保持非降序排列。
C程序代码大全
C程序代码大全Prepared on 21 November 2021<<endl;cout<<"------------------"<<endl;<<endl;cout<<"pi="<<pi<<" r="<<r<<" s="<<s<<endl;}#include <> 1 c<<endl;;int a[10];double xy[10];cout<<"sizeof(str)="<<sizeof(str)<<endl;cout<<"sizeof(a)="<<sizeof(a)<<endl;cout<<"sizeof(xy)="<<sizeof(xy)<<endl;<<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;elsecout<<"Your grade is a E."<<endl;}#include <>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 <>main(){int a,b,Max;.10for(int i=1;i<=10;i++)cout<<i<<" ";cout<<endl;.1for(int j=10;j>=1;j--)cout<<j<<" ";cout<<endl;.9for(int k=1;k<=10;k=k+2)cout<<k<<" ";cout<<endl;.Zfor(char c='A';c<='Z';c++)cout<<c;cout<<endl;.for(float x=0;x<=;x=x+cout<<x<<" ";cout<<endl;.for(float x1=0;x1<=+2;x1=x1+cout<<x1<<" ";cout<<endl;.+100int s=0;for(int n=1;n<=100;n++)s=s+n;cout<<"s="<<s<<endl;}#include<>main(){.+100int s=0,n=1;while(n<=100) {s=s+n;n++;}cout<<"s="<<s<<endl;.+100int s=0,n=0;do {n++;s+=n;}while(n<100);cout<<"s="<<s<<endl;um;cin>>st[i].name;cin>>st[i].maths;cin>>st[i].physics;cin>>st[i].chemistry;}otal=st[i].maths+st[i].physics+st[i].chemistry; um<<'\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<>main(){ame="<<(*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;ame;cout<<"sex:";cin>>(*p).sex;cout<<"age:";cin>>(*p).age;ame="<<(*p).name<<endl;cout<<"(*p).sex="<<(*p).sex<<endl;cout<<"(*p).age="<<(*p).age<<endl;cout<<"-------------------------"<<endl;ame<<'\t';cout<<x[i].sex<<'\t';cout<<x[i].age<<endl;}cout<<"----------------"<<endl;;int int_values[] = {51, 23, 2, 44, 45,0,11};float float_values[] = {, , , , };student st_arr[]={101,"WangLin",92,102,"LiPing",85,103,"ZhaoMin",88};um<<" ";cout<<st_arr[i].name<<" ";cout<<st_arr[i].grade<<endl;}}#include<>otal<a[j].total)swap_Rec(&a[i],&a[j]); <<"\t"<<str_len("This is a test.")<<endl; }#include<>void disp(void); <<endl;}#include<><<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); um;cin>>st[i].name;cin>>st[i].grade;fprintf(fp1,"%d %s %f\n",st[i].num,st[i].name,st[i].grade);}fclose(fp1); <<endl; cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); <<endl;cout<<"Exiting program."<<endl;exit(1); */putc( 'A', stdin );if( ferror( stdin ) ){perror( "Write error" );clearerr( stdin );}/* See if read causes an error. */printf( "Will input cause an error " );c = getc( stdin );if( ferror( stdin ) ){perror( "Read error" );clearerr( stdin );}}#include<>#include<><<endl;for (i=1; i<=MAX; i++) {cin>>x;(x);}<<endl;}void push(float x) <<endl;for (i=1; i<=MAX; i++) {cin>>x;(x);}<<endl;}void push(float x) <<endl;}~stack(void) << endl; << endl;}<< endl; isp_count();delete p;();}#include<><< endl;}~ex_class() {cout << "The Object destroyed." <<endl;}void set_value(int n);void show_val(char *name);} ;<<endl;}#include<>um :";cout<<num<<endl;}};um :";cout<<<<endl;}um="<<num<<endl;}public: um=";cout<<<<endl;}how_value("(*p)obj2");al="<<val<<endl;DispFirst();}};<<endl;}virtual void aFn2(void) {cout<<"aFn2 is in Base class."<<endl;}<<endl;}};<<endl;}<<endl;<<endl;}<<endl;<<endl;}void aFn2(void) {cout<<"aFn2 is in First derived class."<<endl; }};<<endl;}void aFn2(void){cout<<"aFn2 is in Second derived class."<<endl; }};;cout<<"s1: "<<s1<<endl;cout<<"s2: "<<s2<<endl;10.2f10.5f;cout<<"String: "<<string<<endl;cout<<"p : "<<p<<endl;}#include<>#include <>;int n;1.7320534f << endl;}~stack(void) {cout << "Stack Destroyed." << endl;}void push(T);T pop(void);};<< endl;return;}stck[tos++] = i;}template <class T> T stack<T>::pop(void){if(tos==0){cout << "Stack underflow." << endl;return 0;}return stck[--tos];}irst;cout<<","<<(*theIterator).second<<" ";}cout<<endl;irst;cout<<","<<(*theIterator).second<<" ";}cout<<endl;irst;cout<<","<<(*it).second<<" ";}cout<<endl;econd << " ";elsecout << "[err] ";}cout << endl;}}#include <iostream>#include <string>#include <map>using namespace std;econd;cout<<"\t"<<(*theIterator).first<<endl; }econd;cout<<"\t"<<(*i).first<<endl;}econd;cout<<"\t"<<(*it).first<<endl;}econd;cout<<"\t"<<(*i).first<<endl;}}#include <iostream>#include <valarray>#include <>using namespace std;#define ARRAY_SIZE 3 .入栈for (i=0;i<10;i=i+2)(i);if (!()) {cout << "()=20;" << endl;()=20;}//弹出栈中所有的数据并显示cout<<"stack1: ";while (!()) {cout<<()<<" ";();}cout<<endl;}#include <iostream>#include <list>#include <numeric>using namespace std;//创建一个list容器的实例LISTINT,其存放int型数据typedef list<int> LISTINT;void main(void){//用LISTINT创建一个名为listOne的list对象 LISTINT listOne;//指定i为迭代器变量LISTINT::iterator i;LISTINT::reverse_iterator ir;//从前面向listOne容器中添加数据(2);(1);//从后面向listOne容器中添加数据(3);(4);//从前向后显示listOne中的数据for (i = (); i != (); ++i)cout << *i << " ";cout << endl;//从后向后显示listOne中的数据for (ir =();ir!=(); ++ir)cout << *ir << " ";cout << endl;//从键盘上输入数据for (i = (); i != (); ++i) {cout<<"listOne :";cin>>(*i);}//从前向后显示listOne中的数据for (i = (); i != (); ++i)cout << *i << " ";cout << endl;//bidirectional迭代器不允许加减运算// i=()+1;}#include <iostream>#include <iostream>#include <numeric>#include <vector>#include <list>#include <set>using namespace std;//利用类模板生成类实例typedef vector < int > IntArray;typedef list <int> LISTINT;typedef set<int> SET_INT;int add(int a, int b) {return a+b;}//在main()函数中测试accumulate算法void main (){//--------------------------------------------// accumulate算法对于普通数组的计算//--------------------------------------------- int x[]={1,3,5,7,9};cout<<"x[]:";for (int i=0;i<5;i++)cout<<x[i]<<" ";cout<<endl;cout<<"accumulate(x,x+5,0)=";cout<<accumulate(x,x+5,0)<<endl;int val=100;cout<<"val="<<val<<endl;cout<<"accumulate(x,x+5,val)=";cout<<accumulate(x,x+5,val)<<endl;//--------------------------------------------// accumulate算法对于vector容器的计算//--------------------------------------------- //声明intvector容器和迭代器iiIntArray intvector;IntArray::iterator ii;//向intvector容器中插入元素for (i=1; i<=5; i++) {(i);};//显示intvector容器中的元素值和累加结果cout << "intvector: "<<endl;for (ii=();ii !=();++ii)cout<<(*ii)<<" ";cout<<endl;cout<<"accumulate(),(),0)=";cout<<accumulate(),(),0)<<endl;//--------------------------------------------// accumulate算法对于list容器的计算//--------------------------------------------- //声明list容器对象和迭代器LISTINT::iterator iL;LISTINT list1;//向list1容器对象中插入元素并显示(1);(3);(5);(2);(6);//显示list1容器的元素值和累加结果cout << "list1: "<<endl;for (iL=();iL !=();++iL)cout<<(*iL)<<" ";cout<<endl;cout<<"accumulate(),(),0)=";cout<<accumulate(),(),0)<<endl;//--------------------------------------------// accumulate算法对于set容器的计算//--------------------------------------------- //声明set容器对象和迭代器SET_INT set1;SET_INT::iterator si;//向set1容器中插入元素(5);(20);(10);(15);(25);//显示set1容器的元素值和累加结果cout <<"set1: "<<endl;for (si=();si !=();++si)cout<<(*si)<<" ";cout<<endl;cout<<"accumulate(),(),0)=";cout<<accumulate(),(),0)<<endl;cout<<"accumulate(),(),100)=";cout<<accumulate(),(),100)<<endl;}#include <iostream>#include <algorithm>#include <vector>#include <list>#include <set>#define size 10using namespace std;//产生指定范围的整数随机数int getrand(int min,int max) {int m;m=(max-min);m=min+double(rand())/RAND_MAX*m ;return m;}//利用类模板生成实例typedef vector < int > IntArray;typedef list <int> LISTINT;typedef set<int> SET_INT;//在main()函数中测试accumulate算法void main (){//--------------------------------------------// count算法对于普通数组的计算//--------------------------------------------- int x[size];cout<<"x[]:";for (int i=0;i<size;i++) {x[i]=getrand(1,3);cout<<x[i]<<" ";}cout<<endl;cout<<"count(x,x+size,2)=";cout<<count(x,x+size,2)<<endl;cout<<"count(x+2,x+8,2)=";cout<<count(x+2,x+8,2)<<endl;//--------------------------------------------// count算法对于vector容器的计算//声明intvector容器和迭代器iiIntArray intvector;IntArray::iterator ii;//向intvector容器中插入元素for (i=1; i<size; i++) {(getrand(2,6));};//显示intvector容器中的元素值和统计结果cout << "intvector: ";for (ii=();ii !=();++ii)cout<<(*ii)<<" ";cout<<endl;cout<<"count(),(),4)=";cout<<count(),(),4)<<endl;//--------------------------------------------// count算法对于list容器的计算//--------------------------------------------- //声明list容器对象和迭代器LISTINT::iterator iL;LISTINT list1;//向list1容器对象中插入元素并显示for (i=1; i<size; i++) {(getrand(3,5));};//显示list1容器的元素值和统计结果cout << "list1: ";for (iL=();iL !=();++iL)cout<<(*iL)<<" ";cout<<endl;cout<<"count(),(),3)=";cout<<count(),(),3)<<endl;//--------------------------------------------// count算法对于set容器的计算//--------------------------------------------- //声明set容器对象和迭代器SET_INT set1;SET_INT::iterator si;//向set1容器中插入元素for (i=1; i<size; i++) {(getrand(1,10));};//显示set1容器的元素值和统计结果cout <<"set1: ";for (si=();si !=();++si)cout<<(*si)<<" ";cout<<endl;cout<<"count(),(),5)=";cout<<count(),(),5)<<endl;}#include <iostream>#include <algorithm>#include <string>#include <vector>//如果字符串以'S'开头,则返回trueint MatchFirstChar( const string& str){string s("S") ;return s == (0,1) ;}//测试count_if算法void main(){const int VECTOR_SIZE = 8 ;//生成成员类型为strings的vector容器类typedef vector<string > StringVector ;//定义迭代器类型typedef StringVector::iterator StringVectorIt ;//声明vector容器的对象StringVector NamesVect(VECTOR_SIZE) ;//声明迭代器StringVectorIt start, end, it ;int result = 0 ; // 存放统计数据//初始化vector容器NamesVectNamesVect[0] = "She" ;NamesVect[1] = "Sells" ;NamesVect[2] = "Sea" ;NamesVect[3] = "Shells" ;NamesVect[4] = "by" ;NamesVect[5] = "the" ;NamesVect[6] = "Sea" ;NamesVect[7] = "Shore" ;//设置容器的起始位置和终止位置start = () ;end = () ;//显示NamesVect容器的元素cout << "NamesVect: " ;for(it = start; it != end; it++)cout << *it << " " ;cout <<endl ;//统计并显示NamesVect容器的所有元素中以'S'字符开头的字符串 result = count_if(start, end, MatchFirstChar) ;cout << "Number of elements that start with letter \"S\" = " << result << endl ;//显示NamesVect容器[1,6]之间的元素cout <<"NamesVect[1]--NamesVect[6]: " ;for(it =&NamesVect[1]; it != &NamesVect[7]; it++)cout << *it << " " ;cout <<endl ;//统计并显示NamesVect容器的所有元素中以'S'字符开头的字符串cout << "Number of elements that start with letter \"S\" = " << result << endl ;}#include <iostream>#include <algorithm>#include <vector>using namespace std;//利用类模板生成实例typedef vector < int > IntArray;//显示数组void put_array(int x[],int size) {for(int i=0;i<size;i++)cout<<x[i]<<" ";cout<<endl;}//显示vector容器中的元素void put_vector(IntArray v){IntArray::iterator theIterator;for (theIterator=();theIterator!=();++theIterator){cout<<(*theIterator)<<" ";}cout<<endl;}//在main()函数中测试fill和fill_n算法void main (){//--------------------------------------------// fill和fill_n算法对普通数组的计算//---------------------------------------------int x[]={1,3,5,7,9};cout << "x[]: ";put_array(x,5);//填数处理fill(x+1,x+3,2);cout << "fill(x+1,x+3,2): "<<endl;put_array(x,5);fill_n(x,3,8);cout << "fill_n(x,3,8): "<<endl;put_array(x,5);//--------------------------------------------// fill和fill_n算法对于vector容器的计算//---------------------------------------------//声明intvector容器和迭代器iiIntArray intvector;//向intvector容器中插入元素for (int i=1; i<=10; i++) {(i);};//显示intvector容器中的元素值和统计结果cout << "intvector: "<<endl;put_vector(intvector);//填数处理fill(),()+3,2);put_vector(intvector);fill_n(&intvector[5],3,8);cout << "fill_n(&intvector[5],3,8): "<<endl;put_vector(intvector);}#include <iostream>#include <algorithm>#include <vector>#define ARRAY_SIZE 10using namespace std;//利用类模板生成实例typedef vector < int > IntArray;//显示数组void put_array(int x[],int size) {for(int i=0;i<size;i++)cout<<x[i]<<" ";cout<<endl;}//显示vector容器中的元素void put_vector(IntArray v){IntArray::iterator theIterator;for (theIterator=();theIterator!=();++theIterator){cout<<(*theIterator)<<" ";}cout<<endl;}//在main()函数中测试find()算法void main (){int i,value,*p;//--------------------------------------------// find()算法对于普通数组的处理//---------------------------------------------int x[ARRAY_SIZE]={1,3,5,7,9,2,4,6,8,10};cout << "x[]: ";put_array(x,ARRAY_SIZE);//find()算法查找,并显示查找结果for(i=0;i<=2;i++) {cout<<"value=";cin>>value;p=find(x,x+ARRAY_SIZE,value);if (p != x + ARRAY_SIZE) { //查到cout << "First element that matches " << value;cout<< " is at location " << p - x<< endl;}else { //未查到cout << "The sequence does not contain any elements"; cout<< " with value " << value << endl ;}}//声明intvector容器对象IntArray intvector;//向intvector容器中插入元素for (i=1; i<=10; i++) {(i);};//显示intvector容器中的元素值cout << "intvector: ";put_vector(intvector);//find()算法查找,并显示查找结果IntArray::iterator pos;for (i=0;i<=2;i++) {cout<<"value=";cin>>value;pos=find(),(),value);if (pos != ()) { //查到cout << "First element that matches " << value;cout<< " is at location " <<pos - ()<< endl;}else { //未查到cout << "The sequence does not contain any elements"; cout<< " with value " << value << endl ;}}}#include <iostream>#include <algorithm>#include <vector>#define ARRAY_SIZE 10using namespace std;//利用类模板生成实例typedef vector < int > IntArray;//显示数组void put_array(int x[],int size) {for(int i=0;i<size;i++)cout<<x[i]<<" ";}//显示vector容器中的元素void put_vector(IntArray v){IntArray::iterator theIterator;for (theIterator=();theIterator!=();++theIterator){cout<<(*theIterator)<<" ";}}//在main()函数中测试find()_end()算法void main (){int x[ARRAY_SIZE]={1,3,5,7,9,2,4,6,8,10};cout << "x[]: ";put_array(x,ARRAY_SIZE);cout<<endl;int y[]={5,7,9};cout << "y[]: ";put_array(y,3);cout<<endl;// find_end()算法查找,并显示查找结果int *p=find_end(x,x+ARRAY_SIZE,&y[0],&y[2]);if (p != x + ARRAY_SIZE) { //查到cout << "The first element that matches :" ;put_array(y,3);cout<< " is at location in x" << p - x<< endl;}else { //未查到cout << "The sequence does not contain any elements";cout<< " with value " ;put_array(&x[3],3);}//--------------------------------------------// find_end()算法对vector容器的处理//---------------------------------------------//声明intvector容器对象IntArray intvector;//向intvector容器中插入元素for (int i=1; i<=10; i++) {(i);};//显示intvector容器中的元素值cout << "intvector: ";put_vector(intvector);cout<<endl;IntArray temp;(5);(6);(7);cout << "temp: ";put_vector(temp);cout<<endl;// find_end()算法查找,并显示查找结果IntArray::iterator pos;pos=find_end(),(),(),());if (pos != ()) { //查到cout << "The first element that matches ";put_vector(temp);cout<< " is at location in intvector " <<pos - ()<< endl; }else { //未查到cout << "The sequence does not contain any elements";put_vector(temp);cout<< endl ;}}#include <iostream>#include <vector>#include <algorithm>using namespace std;//返回一个Fibonacci数,其由generate_n()算法调用int Fibonacci1(void){static int r;static int f1 = 0;static int f2 = 1;r = f1 + f2 ;f1 = f2 ;f2 = r ;return f1 ;}//返回一个Fibonacci数,其由generate()算法调用int Fibonacci2(void){static int r;static int f1 = 0;static int f2 = 1;r = f1 + f2 ;f1 = f2 ;f2 = r ;return f1 ;}//定义整型数的vector容器类typedef vector<int > IntVector ;//显示vector容器中的元素void put_vector(IntVector v,char *name){IntVector::iterator theIterator;cout<<name<<":"<<endl;for (theIterator=();theIterator!=();++theIterator){cout<<(*theIterator)<<" ";}cout<<endl;}//测试generate()和generate_n()算法void main(){const int VECTOR_SIZE = 15 ;//定义迭代器类typedef IntVector::iterator IntVectorIt ;//声明vector容器对象IntVector Numbers1(VECTOR_SIZE),Numbers2(VECTOR_SIZE); int i ;//初始化vector容器对象Numbers1[i] = i ;//显示vector容器对象的元素cout << "Before calling generate_n:" << endl ;put_vector(Numbers1,"Numbers1");//利用generate_n算法用Fibonacci 数填充vector容器 generate_n(), VECTOR_SIZE, Fibonacci1) ;//显示vector容器对象的元素cout << "After calling generate_n:" << endl ;put_vector(Numbers1,"Numbers1");//利用generate算法用Fibonacci 数填充vector容器generate(),(), Fibonacci2) ;//显示vector容器对象的元素cout << "After calling generate:" << endl ;put_vector(Numbers2,"Numbers2");}#include <iostream>#include <algorithm>#include <vector>using namespace std;//利用类模板生成实例typedef vector < int > IntArray;//显示数组void put_array(int x[],int size) {for(int i=0;i<size;i++)cout<<x[i]<<" ";cout<<endl;}//显示vector容器中的元素void put_vector(IntArray v){IntArray::iterator theIterator;for (theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<<" ";}cout<<endl;}//在main()函数中测试reverse()和reverse_copy()算法void main (){//--------------------------------------------// reverse()和reverse_copy()算法对普通数组处理//---------------------------------------------int x[]={1,3,5,7,9};cout<<"x[]:";put_array(x,5);//reverse()反转x数组并显示reverse(x,x+5);put_array(x,5);int y[]={2,4,6,8,10};cout<<"y[]:";put_array(y,5);//reverse_copy()反转y数组的部分元素并拷贝到x数组第2个元素位置 reverse_copy(y+1,y+3,x+1);cout<<"x[]:";put_array(x,5);cout<<"y[]:";put_array(y,5);//--------------------------------------------// reverse()和reverse_copy()算法对vector容器的处理//---------------------------------------------//声明intvector容器和迭代器iiIntArray intvector;//向intvector容器中插入元素for (int i=1; i<=10; i++) {(i);};//显示intvector容器中的元素值cout << "intvector: "<<endl;put_vector(intvector);//reverse()对于vector容器的处理reverse(),());cout << "intvector: "<<endl;put_vector(intvector);// reverse_copy对于vector容器的处理IntArray temp(5);reverse_copy()+2,()+7,());cout << "temp: "<<endl;put_vector(temp);}#include <iostream>#include <algorithm>#include <vector>#include <>#define ARRAY_SIZE 15using namespace std;//定义整型数的vector容器类typedef vector<int > IntVector ;//显示数组void put_array(int x[],int size) {for(int i=0;i<size;i++)cout<<x[i]<<" ";cout<<endl;}//显示vector容器中的元素void put_vector(IntVector v,char *name){IntVector::iterator theIterator;for (theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<<" ";}cout<<endl;}//产生指定范围的整数随机数int getrand(int min,int max) {int m;m=(max-min);m=min+double(rand())/RAND_MAX*m ;return m;}//在main()函数中测试sort()和partial_sort()算法void main (){int i;//--------------------------------------------// sort()和partial_sort()算法对普通数组处理//---------------------------------------------//sort()算法处理数组,并显示int x[ARRAY_SIZE];for (i=0;i<ARRAY_SIZE;i++) {x[i]=getrand(1,20);}cout<<"x[]:";put_array(x,ARRAY_SIZE);sort(x,x+ARRAY_SIZE);cout<<"sort(x,x+ARRAY_SIZE):"<<endl;put_array(x,ARRAY_SIZE);//partial_sort()算法对于数组进行处理int y[ARRAY_SIZE];for (i=0;i<ARRAY_SIZE;i++) {y[i]=getrand(1,30) ;}cout<<"y[]:";put_array(y,ARRAY_SIZE);partial_sort(y+2,y+7,y+ARRAY_SIZE);cout<<"partial_sort(y+2,y+7,y+ARRAY_SIZE):"<<endl; put_array(y,ARRAY_SIZE);//--------------------------------------------// sort()和partial_sort()算法对vector容器的处理//---------------------------------------------IntVector Numbers1,Numbers2;for(i=0;i<15;i++) {(getrand(1,30));(getrand(1,30));}put_vector(Numbers1,"Numbers1");put_vector(Numbers2,"Numbers2");//sort()算法处理并显示sort(),());cout<<"After call sort():"<<endl;put_vector(Numbers1,"Numbers1");//partial_sort()算法处理并显示partial_sort()+2,()+7,());。
经典c程序100例-
经典c程序100例-菜鸟变高手必看!(附下载)作者:佚名责任编辑:lujiezhen【程序91】题目:时间函数举例11.程序分析:2.程序源代码:#include "stdio.h"#include "time.h"void main(){ time_t lt; /*define a longint time varible*/lt=time(NULL);/*system time and date*/printf(ctime(<)); /*english format output*/printf(asctime(localtime(<)));/*tranfer to tm*/ printf(asctime(gmtime(<))); /*tranfer to Greenwich time*/}==============================================================【程序92】题目:时间函数举例21.程序分析:2.程序源代码:/*calculate time*/#include "time.h"#include "stdio.h"main(){ time_t start,end;int i;start=time(NULL);for(i=0;i<3000;i++){ printf("\1\1\1\1\1\1\1\1\1\1\n");}end=time(NULL);printf("\1: The different is %6.3f\n",difftime(end,start));}==============================================================【程序93】题目:时间函数举例31.程序分析:2.程序源代码:/*calculate time*/#include "time.h"#include "stdio.h"main(){ clock_t start,end;int i;double var;start=clock();for(i=0;i<10000;i++){ printf("\1\1\1\1\1\1\1\1\1\1\n");}end=clock();printf("\1: The different is %6.3f\n",(double)(end-start));}==============================================================【程序94】题目:时间函数举例4,一个猜数游戏,判断一个人反应快慢。
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程序代码大全
<<endl;cout<<------------------<<endl; <<endl;cout<<pi=<<pi<< r=<<r<< s=<<s<<endl; }#include <> 1 c<<endl; ;int a[10]; double xy[10];cout<<sizeof(str)=<<sizeof(str)<<endl;cout<<sizeof(a)=<<sizeof(a)<<endl; cout<<sizeof(xy)=<<sizeof(xy)<<endl; <<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 cout<<Your grade is aE.<<endl; }#include <> main() {int n;cout<<=; cin>>n;if (n>=0 && n<=100 &&n%2==0) cout<<=<<n<<endl; elsecout<<The <<n<< is out of range!<<endl; } #include <> main() { int a,b,Max; .10for(int i=1;i<=10;i++) cout<<i<< ; cout<<endl; .1for(int j=10;j>=1;j--) cout<<j<< ; cout<<endl; .9for(int k=1;k<=10;k=k+2) cout<<k<< ; cout<<endl; .Z for(char c='A';c<='Z';c++) cout<<c; cout<<endl;.for(float x=0;x<=;x=x+ cout<<x<< ; cout<<endl; .for(float x1=0;x1<=+2;x1=x1+ cout<<x1<< ;cout<<endl; .+100 int s=0;for(int n=1;n<=100;n++) s=s+n;cout<<s=<<s<<endl; }#include<> main() {.+100int s=0,n=1; while(n<=100) { s=s+n; n++; } cout<<s=<<s<<endl; .+100int s=0,n=0; do { n++; s+=n; }while(n<100);cout<<s=<<s<<endl; um;cin>>st[i].name; cin>>st[i].maths; cin>>st[i].physics; cin>>st[i].chemistry; } otal=st[i].maths+st[i].physics+st[i].chemistry; um<<'\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<> main() {ame=<<(*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;ame;cout<<sex:; cin>>(*p).sex; cout<<age:; cin>>(*p).age;ame=<<(*p).name<<endl;cout<<(*p).sex=<<(*p).sex<<endl; cout<<(*p).age=<<(*p).age<<endl; cout<<-------------------------<<endl; ame<<'\t';cout<<x[i].sex<<'\t'; cout<<x[i].age<<endl; } cout<<----------------<<endl; ;int int_values[] = {51, 23, 2, 44, 45,0,11}; float float_values[] = {, , , , }; student st_arr[]={101,WangLin,92,102,LiPing,85,103,ZhaoMin,88}; um<< ;cout<<st_arr[i].name<< ; cout<<st_arr[i].grade<<endl; } } #include<> otal<a[j].total)swap_Rec(&a[i],&a[j]); <<\<<str_len(This is atest.)<<endl; }#include<>void disp(void); <<endl; }#include<> <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); um;cin>>st[i].name; cin>>st[i].grade;fprintf(fp1,%d %s %f\n,st[i].num,st[i].name,st[i].grade);} fclose(fp1); <<endl; cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); <<endl;cout<<Exiting program.<<endl; exit(1); */ putc( 'A', stdin );if( ferror( stdin ) ) {perror( Write error ); clearerr( stdin ); } /* See if read causes an error. */printf( Will input cause an error? ); c = getc( stdin );if( ferror( stdin ) ) {perror( Read error ); clearerr( stdin ); } }#include<> #include<> <<endl;for (i=1; i<=MAX; i++) { cin>>x; (x); }<<endl; } void push(float x) <<endl; for (i=1; i<=MAX; i++) { cin>>x; (x); } <<endl; } void push(float x) <<endl; }~stack(void) << endl; << endl; }<< endl; isp_count(); delete p; (); }#include<> << endl; }~ex_class() { cout << The Object destroyed. <<endl; } void set_value(int n);void show_val(char *name); } ; <<endl; }#include<> um :; cout<<num<<endl; } }; um :;cout<<<<endl; }um=<<num<<endl; }public: um=;cout<<<<endl; } how_value((*p)obj2); al=<<val<<endl;DispFirst(); } }; <<endl; }virtual void aFn2(void) { cout<<aFn2 is in Baseclass.<<endl; }<<endl; } }; <<endl; }<<endl; <<endl; }<<endl; <<endl; }void aFn2(void) {cout<<aFn2 is in First derived class.<<endl; } };<<endl; }void aFn2(void){cout<<aFn2 is in Second derived class.<<endl; } }; ;cout<<s1: <<s1<<endl; cout<<s2: <<s2<<endl; 10.2f10.5f;cout<<String: <<string<<endl; cout<<p : <<p<<endl; }#include<> #include <> ;int n; 1.7320534f << endl; }~stack(void) {cout << Stack Destroyed. << endl; }void push(T); T pop(void); }; << endl;return; }stck[tos++] = i; }template <class T> T stack<T>::pop(void) {if(tos==0) {cout << Stack underflow. << endl; return 0; } return stck[--tos]; } irst;cout<<,<<(*theIterator).second<< ; }cout<<endl; irst;cout<<,<<(*theIterator).second<< ; }cout<<endl; irst;cout<<,<<(*it).second<< ; } cout<<endl;econd << ;else cout << [err] ; }cout << endl; } }#include <iostream> #include <string> #include <map> using namespace std; econd; cout<<\<<(*theIterator).first<<endl; } econd; cout<<\ <<(*i).first<<endl; } econd; cout<<\<<(*it).first<<endl; } econd; cout<<\<<(*i).first<<endl; } }#include <iostream> #include <valarray>#include <> using namespace std; #define ARRAY_SIZE 3 .入栈for (i=0;i<10;i=i+2) (i); if (!()) { cout << ()=20; << endl;()=20; } //弹出栈中所有的数据并显示cout<<stack1: ;while (!()) { cout<<()<< ; (); } cout<<endl; }#include <iostream> #include <list>#include <numeric> using namespace std;//创建一个list容器的实例LISTINT,其存放int型数据typedef list<int> LISTINT; void main(void) {//用LISTINT创建一个名为listOne的list对象LISTINT listOne;//指定i为迭代器变量LISTINT::iterator i;LISTINT::reverse_iterator ir; //从前面向listOne容器中添加数据(2); (1); //从后面向listOne容器中添加数据(3); (4);//从前向后显示listOne中的数据for (i = (); i != (); ++i) cout << *i << ; cout << endl; //从后向后显示listOne中的数据for (ir=();ir!=(); ++ir) cout << *ir << ; cout << endl; //从键盘上输入数据for (i = (); i != (); ++i) { cout<<listOne :;cin>>(*i); } //从前向后显示listOne中的数据for (i = (); i != (); ++i) cout << *i << ; cout << endl; //bidirectional迭代器不允许加减运算// i=()+1; }#include <iostream> #include <iostream> #include <numeric> #include <vector>#include <list> #include <set> using namespace std; //利用类模板生成类实例typedef vector < int > IntArray; typedef list <int> LISTINT; typedef set<int>SET_INT; int add(int a, int b) { return a+b; }//在main()函数中测试accumulate算法void main () {//--------------------------------------------// accumulate算法对于普通数组的计算//---------------------------------------------int x[]={1,3,5,7,9}; 潣瑵?硜嵛尺※for (int i=0;i<5;i++) cout<<x[i]<< ; cout<<endl;cout<<accumulate(x,x+5,0)=; cout<<accumulate(x,x+5,0)<<endl; intval=100; cout<<val=<<val<<endl;cout<<accumulate(x,x+5,val)=; cout<<accumulate(x,x+5,val)<<endl;//--------------------------------------------// accumulate算法对于vector容器的计算//---------------------------------------------//声明intvector容器和迭代器ii IntArray intvector; IntArray::iterator ii; //向intvector容器中插入元素for (i=1; i<=5; i++) { (i); };//显示intvector容器中的元素值和累加结果cout << intvector: <<endl;for (ii=();ii !=();++ii) cout<<(*ii)<< ; cout<<endl;cout<<accumulate(),(),0)=; cout<<accumulate(),(),0)<<endl;//--------------------------------------------// accumulate算法对于list容器的计算//---------------------------------------------//声明list容器对象和迭代器LISTINT::iterator iL; LISTINT list1;//向list1容器对象中插入元素并显示(1); (3); (5); (2); (6); //显示list1容器的元素值和累加结果cout << list1: <<endl;for (iL=();iL !=();++iL) cout<<(*iL)<< ; cout<<endl;cout<<accumulate(),(),0)=; cout<<accumulate(),(),0)<<endl;//-------------------------------------------- // accumulate算法对于set容器的计算//---------------------------------------------//声明set容器对象和迭代器SET_INT set1;SET_INT::iterator si;//向set1容器中插入元素(5); (20); (10); (15); (25); //显示set1容器的元素值和累加结果cout <<set1: <<endl; for(si=();si !=();++si) cout<<(*si)<< ; cout<<endl;cout<<accumulate(),(),0)=; cout<<accumulate(),(),0)<<endl;cout<<accumulate(),(),100)=; cout<<accumulate(),(),100)<<endl; }#include <iostream> #include <algorithm> #include <vector> #include <list>#include <set> #define size 10using namespace std; //产生指定范围的整数随机数int getrand(int min,int max) { int m;m=(max-min);m=min+double(rand())/RAND_MAX*m ; return m; } //利用类模板生成实例typedef vector < int > IntArray; typedef list <int> LISTINT; typedef set<int> SET_INT; //在main()函数中测试accumulate算法void main () {//-------------------------------------------- // count算法对于普通数组的计算//---------------------------------------------int x[size]; 潣瑵?硜嵛尺※for (int i=0;i<size;i++) { x[i]=getrand(1,3); cout<<x[i]<< ; }cout<<endl;cout<<count(x,x+size,2)=; cout<<count(x,x+size,2)<<endl;cout<<count(x+2,x+8,2)=; cout<<count(x+2,x+8,2)<<endl;//-------------------------------------------- // count算法对于vector容器的计算//---------------------------------------------//声明intvector容器和迭代器ii IntArray intvector; IntArray::iterator ii; //向intvector容器中插入元素for (i=1; i<size; i++){ (getrand(2,6)); };//显示intvector容器中的元素值和统计结果cout << intvector: ; for (ii=();ii !=();++ii) cout<<(*ii)<< ; cout<<endl;cout<<count(),(),4)=; cout<<count(),(),4)<<endl;//-------------------------------------------- // count算法对于list容器的计算//---------------------------------------------//声明list容器对象和迭代器LISTINT::iterator iL; LISTINT list1; //向list1容器对象中插入元素并显示for (i=1; i<size; i++) { (getrand(3,5)); }; //显示list1容器的元素值和统计结果cout << list1: ;for (iL=();iL !=();++iL) cout<<(*iL)<< ; cout<<endl;cout<<count(),(),3)=; cout<<count(),(),3)<<endl;//-------------------------------------------- // count算法对于set容器的计算//---------------------------------------------//声明set容器对象和迭代器SET_INT set1;SET_INT::iterator si; //向set1容器中插入元素for (i=1; i<size; i++) { (getrand(1,10)); }; //显示set1容器的元素值和统计结果cout <<set1: ;for (si=();si !=();++si) cout<<(*si)<< ; cout<<endl;cout<<count(),(),5)=; cout<<count(),(),5)<<endl; }#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std;//如果字符串以'S'开头,则返回true int MatchFirstChar( const string& str) { string s(S) ; return s == (0,1) ; } //测试count_if算法void main() {const int VECTOR_SIZE = 8 ; //生成成员类型为strings的vector容器类typedef vector<string > StringVector ; //定义迭代器类型typedef StringVector::iterator StringVectorIt ; //声明vector容器的对象StringVector NamesVect(VECTOR_SIZE) ; //声明迭代器StringVectorIt start, end, it ; int result = 0 ; // 存放统计数据//初始化vector容器NamesVect NamesVect[0] = She ; NamesVect[1] = Sells ; NamesVect[2] = Sea ; NamesVect[3] = Shells ; NamesVect[4] = y ; NamesVect[5] = he ; NamesVect[6] = Sea ; NamesVect[7] = Shore ;//设置容器的起始位置和终止位置start = () ; end = () ; //显示NamesVect容器的元素cout << NamesVect: ; for(it = start; it != end; it++) cout << *it << ; cout <<endl ; //统计并显示NamesVect容器的所有元素中以'S'字符开头的字符串result = count_if(start, end, MatchFirstChar) ;cout << Number of elements that start with letter \S\ = << result << endl ; //显示NamesVect容器[1,6]之间的元素cout<<NamesVect[1]--NamesVect[6]: ;for(it =&NamesVect[1]; it != &NamesVect[7]; it++) cout << *it<< ; cout <<endl ; //统计并显示NamesVect容器的所有元素中以'S'字符开头的字符串result = count_if(&NamesVect[1], &NamesVect[7], MatchFirstChar) ;cout << Number of elements that start with letter \S\ = << result << endl ; }#include <iostream> #include <algorithm> #include <vector> using namespace std; //利用类模板生成实例typedef vector < int > IntArray; //显示数组voidput_array(int x[],int size) { for(int i=0;i<size;i++) cout<<x[i]<< ; cout<<endl; }//显示vector容器中的元素void put_vector(IntArray v) {IntArray::iterator theIterator; for(theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<< ;}cout<<endl; } //在main()函数中测试fill和fill_n算法void main () {//-------------------------------------------- // fill和fill_n算法对普通数组的计算//---------------------------------------------int x[]={1,3,5,7,9}; 潣瑵??硜嵛?? put_array(x,5); //填数处理fill(x+1,x+3,2);cout <<ill(x+1,x+3,2): <<endl; put_array(x,5); fill_n(x,3,8);cout <<ill_n(x,3,8): <<endl; put_array(x,5);//--------------------------------------------// fill和fill_n算法对于vector容器的计算//---------------------------------------------//声明intvector容器和迭代器ii IntArray intvector; //向intvector容器中插入元素for (int i=1; i<=10; i++) { (i); };//显示intvector容器中的元素值和统计结果cout << intvector: <<endl; put_vector(intvector); //填数处理fill(),()+3,2);cout <<ill(),()+3,2): <<endl;put_vector(intvector); fill_n(&intvector[5],3,8);cout <<ill_n(&intvector[5],3,8): <<endl; put_vector(intvector); }#include <iostream> #include <algorithm> #include <vector>#define ARRAY_SIZE 10 using namespace std; //利用类模板生成实例typedef vector < int > IntArray; //显示数组void put_array(int x[],int size) { for(inti=0;i<size;i++) cout<<x[i]<< ; cout<<endl; } //显示vector容器中的元素void put_vector(IntArray v) {IntArray::iterator theIterator; for(theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<< ;}cout<<endl; } //在main()函数中测试find()算法void main () { inti,value,*p;//-------------------------------------------- // find()算法对于普通数组的处理//---------------------------------------------int x[ARRAY_SIZE]={1,3,5,7,9,2,4,6,8,10}; 潣瑵??硜嵛??put_array(x,ARRAY_SIZE); //find()算法查找,并显示查找结果for(i=0;i<=2;i++) { cout<<value=; cin>>value;p=find(x,x+ARRAY_SIZE,value); if (p != x + ARRAY_SIZE) { //查到cout << First element that matches << value;cout<< is at location << p - x<< endl; }else { //未查到cout<< The sequence does not contain any elements; cout<< with value << value << endl ; } }//--------------------------------------------// find()算法对于vector容器的处理//---------------------------------------------//声明intvector容器对象IntArray intvector; //向intvector容器中插入元素for (i=1; i<=10; i++) { (i); }; //显示intvector容器中的元素值cout << intvector: ; put_vector(intvector); //find()算法查找,并显示查找结果IntArray::iterator pos; for (i=0;i<=2;i++){ cout<<value=; cin>>value;pos=find(),(),value); if (pos != ()) { //查到cout << First element that matches << value; cout<< is at location<<pos - ()<< endl; }else { //未查到cout << The sequence does not contain any elements; cout<< with value << value << endl ; } } }#include <iostream> #include <algorithm> #include <vector>#define ARRAY_SIZE 10 using namespace std; //利用类模板生成实例typedef vector < int > IntArray; //显示数组void put_array(int x[],int size) { for(inti=0;i<size;i++) cout<<x[i]<< ; } //显示vector容器中的元素voidput_vector(IntArray v) {IntArray::iterator theIterator; for(theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<< ;} } //在main()函数中测试find()_end()算法void main () {//--------------------------------------------// find_end()算法对普通数组的处理//---------------------------------------------int x[ARRAY_SIZE]={1,3,5,7,9,2,4,6,8,10}; 潣瑵??硜嵛??put_array(x,ARRAY_SIZE); cout<<endl; int y[]={5,7,9}; cout << y[]: ; put_array(y,3); cout<<endl; // find_end()算法查找,并显示查找结果int *p=find_end(x,x+ARRAY_SIZE,&y[0],&y[2]); if (p != x + ARRAY_SIZE) { //查到cout << The first element that matches : ;put_array(y,3);cout<< is at location in x << p - x<< endl; }else { //未查到cout << The sequence does not contain any elements; cout<< with value ;put_array(&x[3],3); } //-------------------------------------------- // find_end()算法对vector容器的处理//---------------------------------------------//声明intvector容器对象IntArray intvector; //向intvector容器中插入元素for (int i=1; i<=10; i++) { (i); }; //显示intvector容器中的元素值cout << intvector: ; put_vector(intvector); cout<<endl; IntArray temp; (5); (6); (7);cout << emp: ; put_vector(temp); cout<<endl; // find_end()算法查找,并显示查找结果IntArray::iterator pos; pos=find_end(),(),(),()); if (pos != ()) { //查到cout << The first element that matches ;put_vector(temp);cout<< is at location in intvector <<pos - ()<< endl; } else { //未查到cout << The sequence does not contain any elements; cout<< with value ;put_vector(temp); cout<< endl ; } }#include <iostream> #include <vector> #include <algorithm> using namespace std; //返回一个Fibonacci数,其由generate_n()算法调用int Fibonacci1(void) { static int r;static int f1 = 0; static int f2 = 1; r = f1 + f2 ; f1 = f2 ; f2 = r ; return f1 ; }//返回一个Fibonacci数,其由generate()算法调用int Fibonacci2(void) { static int r;static int f1 = 0; static int f2 = 1; r = f1 + f2 ; f1 = f2 ; f2 = r ; return f1 ; }//定义整型数的vector容器类typedef vector<int > IntVector ; //显示vector 容器中的元素void put_vector(IntVector v,char *name) {IntVector::iterator theIterator; cout<<name<<:<<endl;for(theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<< ;}cout<<endl; } //测试generate()和generate_n()算法void main() {const int VECTOR_SIZE = 15 ; //定义迭代器类typedef IntVector::iterator IntVectorIt ; //声明vector容器对象IntVector Numbers1(VECTOR_SIZE),Numbers2(VECTOR_SIZE); int i ; //初始化vector容器对象for(i = 0; i < VECTOR_SIZE; i++)Numbers1[i] = i ; //显示vector容器对象的元素cout << Before calling generate_n: << endl ; put_vector(Numbers1,Numbers1); //利用generate_n算法用Fibonacci 数填充vector容器generate_n(), VECTOR_SIZE, Fibonacci1) ; //显示vector容器对象的元素cout << After calling generate_n: << endl ; put_vector(Numbers1,Numbers1); //利用generate算法用Fibonacci 数填充vector容器generate(),(), Fibonacci2) ; //显示vector容器对象的元素cout << After calling generate: << endl ;put_vector(Numbers2,Numbers2); }#include <iostream> #include <algorithm> #include <vector> using namespace std; //利用类模板生成实例typedef vector < int > IntArray; //显示数组voidput_array(int x[],int size) { for(int i=0;i<size;i++) cout<<x[i]<< ; cout<<endl; } //显示vector容器中的元素void put_vector(IntArray v) { IntArray::iterator theIterator; for(theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<< ;} cout<<endl; } //在main()函数中测试reverse()和reverse_copy()算法void main () {//--------------------------------------------// reverse()和reverse_copy()算法对普通数组处理//---------------------------------------------int x[]={1,3,5,7,9}; 潣瑵?硜嵛尺※put_array(x,5); //reverse()反转x数组并显示reverse(x,x+5); 潣瑵?硜嵛尺※put_array(x,5); int y[]={2,4,6,8,10}; cout<<y[]:; put_array(y,5); //reverse_copy()反转y数组的部分元素并拷贝到x数组第2个元素位置reverse_copy(y+1,y+3,x+1); 潣瑵?硜嵛尺※put_array(x,5);cout<<y[]:; put_array(y,5);//--------------------------------------------// reverse()和reverse_copy()算法对vector容器的处理//---------------------------------------------//声明intvector容器和迭代器ii IntArray intvector; //向intvector容器中插入元素for (int i=1; i<=10;i++) { (i); }; //显示intvector容器中的元素值cout << intvector: <<endl; put_vector(intvector); //reverse()对于vector容器的处理reverse(),());cout << intvector: <<endl; put_vector(intvector); // reverse_copy对于vector容器的处理IntArray temp(5);reverse_copy()+2,()+7,()); cout << emp: <<endl;put_vector(temp); }#include <iostream> #include <algorithm> #include <vector> #include <>#define ARRAY_SIZE 15 using namespace std; //定义整型数的vector容器类typedef vector<int > IntVector ; //显示数组void put_array(int x[],int size){ for(int i=0;i<size;i++) cout<<x[i]<< ; cout<<endl; } //显示vector容器中的元素void put_vector(IntVector v,char *name) {IntVector::iterator theIterator; cout<<name<<: ;for(theIterator=();theIterator!=();++theIterator){ cout<<(*theIterator)<< ;}cout<<endl; } //产生指定范围的整数随机数int getrand(int min,int max) { int m;m=(max-min);m=min+double(rand())/RAND_MAX*m ; return m; } //在main()函数中测试sort()和partial_sort()算法void main () {int i;//--------------------------------------------// sort()和partial_sort()算法对普通数组处理//---------------------------------------------//sort()算法处理数组,并显示int x[ARRAY_SIZE];for (i=0;i<ARRAY_SIZE;i++) { x[i]=getrand(1,20); }潣瑵?硜嵛尺※put_array(x,ARRAY_SIZE); sort(x,x+ARRAY_SIZE);cout<<sort(x,x+ARRAY_SIZE):<<endl; put_array(x,ARRAY_SIZE);//partial_sort()算法对于数组进行处理int y[ARRAY_SIZE];for (i=0;i<ARRAY_SIZE;i++) { y[i]=getrand(1,30) ; }cout<<y[]:;put_array(y,ARRAY_SIZE);partial_sort(y+2,y+7,y+ARRAY_SIZE);cout<<partial_sort(y+2,y+7,y+ARRAY_SIZE):<<endl;put_array(y,ARRAY_SIZE); //--------------------------------------------// sort()和partial_sort()算法对vector容器的处理//---------------------------------------------IntVector Numbers1,Numbers2;for(i=0;i<15;i++) { (getrand(1,30)); (getrand(1,30)); }put_vector(Numbers1,Numbers1); put_vector(Numbers2,Numbers2); //sort()算法处理并显示sort(),()); cout<<After call sort():<<endl;put_vector(Numbers1,Numbers1); //partial_sort()算法处理并显示partial_sort()+2,()+7,());cout<<After call partial_sort():<<endl; put_vector(Numbers2,Numbers2); } #include <iostream> #include <algorithm> #include <> #include <> #define ARRAY_SIZE 15 using namespace std; //显示数组void put_array(int x[],int size) { for(int i=0;i<size;i++) cout<<x[i]<< ; cout<<endl; } //产生指定范围的整数随机数int getrand(int min,int max) { int m; m=(max-min);m=min+double(rand())/RAND_MAX*m ; return m; }//在main()函数中测试max_element()和min_element()算法void main () { //声明变量和数组int i;int x[ARRAY_SIZE]; //用1到100的随机数初始化数组,并显示srand( (unsigned)time( NULL ) ); for (i=0;i<ARRAY_SIZE;i++){ x[i]=getrand(1,100); }潣瑵?硜嵛尺※put_array(x,ARRAY_SIZE); //对数组x使用max_element()算法,并显示int *pMax=max_element(x,x+ARRAY_SIZE); cout<<pMax=<<pMax<<endl; cout<<Location=<<(pMax-x)<<endl; cout<<*pMax=<<(*pMax)<<endl; //对数组x使用min_element()算法,并显示int *pMin=min_element(x,x+ARRAY_SIZE); cout<<pMin =<<pMin<<endl; cout<<Location=<<(pMin-x)<<endl; cout<<*pMin =<<(*pMin)<<endl; }。
经典C语言编程100例
C 语言编程经典 100 例A:【程序1】题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。
组成所有的排列后再去掉不满足条件的排列。
2.程序源代码:main(){int i,j,k;printf(“\n“);for(i=1;i〈5;i++) /*以下为三重循环*/for(j=1;j〈5;j++)for (k=1;k〈5;k++){if (i!=k&&i!=j&&j!=k) /*确保i、j、k三位互不相同*/printf(“%d,%d,%d\n“,i,j,k);}}==============================================================【程序2】题目:企业发放的奖金根据利润提成。
利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?1.程序分析:请利用数轴来分界,定位。
注意定义时需把奖金定义成长整型。
2.程序源代码:main(){long int i;int bonus1,bonus2,bonus4,bonus6,bonus10,bonus;scanf(“%ld“,&i);bonus1=100000*0.1;bonus2=bonus1+100000*0.75;bonus4=bonus2+200000*0.5;bonus6=bonus4+200000*0.3;bonus10=bonus6+400000*0.15;if(i〈=100000)bonus=i*0.1;else if(i〈=200000)bonus=bonus1+(i-100000)*0.075;else if(i〈=400000)bonus=bonus2+(i-200000)*0.05;else if(i〈=600000)bonus=bonus4+(i-400000)*0.03;else if(i〈=1000000)bonus=bonus6+(i-600000)*0.015;elsebonus=bonus10+(i-1000000)*0.01;printf(“bonus=%d“,bonus);}==============================================================【程序3】题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?1.程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足如下条件,即是结果。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#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的引用。