直齿花键C语言程序源代码
- 格式:doc
- 大小:85.00 KB
- 文档页数:17
C语言简单程序代码以下代码亲自运行成功,可黏贴到vc中运行gets和puts函数 #include\void main() { char str[20]; gets(str);//输入字符串 puts(str);//输出字符串 }整型、字符、字符串、一维数组的初始化、输入和输出 #include\#include\voidmain() { int i = 2; printf(\请输入一个int型\ int ii; scanf(\ printf(\//字符类型 char c = 'x'; printf(\请输入一个char型\ char cc; scanf(\ //cc = getchar(); printf(\ //putchar(cc); //字符串型 char str[] = \ printf(\请输入一个字符串类型\ char strr[100];//必须指定大小 //scanf(\字符数组名就代表了地址gets(strr);//字符串输入函数 //printf(\ puts(strr); //一维数组int a[5] = {1,2,3,4,5}; for(int j = 0;j < 5;j ++)printf(\ int b[3]; printf(\请输入三个数字\\n\ for(int k = 0;k < 3;k ++) { scanf(\ } printf(\输入三个数字是:\\n\ for(k = 0;k < 3;k ++) printf(\}//结构体 struct student { char name[9]; int score[3];//存放3门课成绩 }; student stu[2];//定义两个学生的数组 for(int i = 0;i < 2;i ++){ printf(\请输入第%d个学生的信息:\\n\ printf(\姓名:\ scanf(\ for(int j= 0;j < 3;j ++) { printf(\成绩%d:\ scanf(\ } }字符串输出void main() { char str[]= \ int i; char c; for(i = 0;i <strlen(str);i++) { printf(\输出abcd } for(i = 0;(c = str[i]) != '\\0';i++) { printf(\输出4个# } }单个输出整数的每个数字 #include\void main() { int a = 12342139; int i;do { i = a ; printf(\ a = a / 10; }while(a); }整型,字符串,数组的指针及输出 #include\#include\#include\ int *p; voidmain() {/* char *str = \最初指向V str++; printf(\输出后面的字符串zz int a[3]= {1,2,3}; p=a;//最初指向1 p++;//移动一个,指向2 printf(\*/ char * month[3] = {\ month[0]++; printf(\输出Wie:anuary }各数值类型所占字节数 #include\void main() { printf(\ printf(\ printf(\ printf(\ printf(\ printf(\}字符串和指针 #include\#include\#include\void main() { char *str = \最初指向V str++;//后来指向x str++;//变成指向z printf(\输出单个字符z printf(\输出后面的字符串zz }递增操作符#include\void main() { int a = 2; int b = 0; int c = 0; b = a++;//2,先赋值后加1 c = ++a;//4,先加1后赋值printf(\}函数判断最大值int max(int a,int b,int c) { int temp; temp = a > b ? a : b; temp = temp > c ? temp : c; return temp; }输入字符,如果是大写变成小写 #include\void main() { char ch; printf(\请输入一个字母\\n\ scanf(\ch = (ch >= 'A' && ch <= 'Z')?(ch + 32):ch;//小写比大写大32 printf(\ }输入一行字符,判断其中的英文字母,空格,数字和其他字符的个数 char ch; while((ch = getchar()) != '\\n') { if((ch >= 'A' && ch <= 'Z')||(ch >= 'a' && ch <= 'z') letters ++; else if(ch == ' ') space ++; else if(ch >= '0' && ch <= '9') digit ++; else others ++; }猜数字#include\#include\void main() { int count = 0;//猜数次数感谢您的阅读,祝您生活愉快。
C 经典程序代码大全#include const float PI=3.1416; //声明常量(只读变量)PI为3.1416 float fCir_L(float); //声明自定义函数fCir_L()的原型 float fCir_S(float); //声明自定义函数fCir_S()的原型 //以下是main()函数 main(){ float r,l,s; //声明3个变量 cout>r; //键盘输入l=fCir_L(r); //计算圆的周长,赋值给变量l s=fCir_S(r); //计算圆的面积,赋值给变量s cout=0.0)//如果参数大于0,则计算圆的周长 z=2*PI*x; return(z); //返回函数值 } //定义计算圆的面积的函数fCir_S() float fCir_S(float x){ float z=-1.0; //声明局部变量 if (x>=0.0)//如果参数大于0,则计算圆的面积 z=PI*x*x; return(z); //返回函数值 } /* Program: P1-2.CPP Written by: Hap Date written: 02:11:10 */#include void main(void){ double s1,s2,s3; s1=1.5; /* 对变量s1赋值*/ cout main(){ double r=1.0; cout>r; //键盘输入 l=2*3.1416*r; //计算圆的周长,赋值给变量l cout //包含iostream.h头文件 void main(){ //输出字符常量.变量和字符串 char c1= A ; cout //包含iostream.h头文件 main(){ //输入输出字符 char c; cin>>c; cout>n; cout>x; cout>n; cout>c>>n>>x; cout //包含iostream.h头文件 main() { //声明整型变量 int a,b; //从键盘上为整型变量赋值cout>a; cout>b; //整型数的算术运算 cout //包含iostream.h 头文件 main(){ //声明变量,并初始化 int a=010,b=10,c=0X10; //以进制形式显示数据 cout>a; cout>b; cout>c; cout //包含iostream.h头文件 #include // iomanip.h头文件包含setprecision()的定义 main(){ //float型变量的声明.输入.计算和输出 float fx,fy; cout>fx; cout>fy; cout>dx; cout>dy; cout //包含iostream.h 头文件 main(){ //字符类型变量的声明 char c1= A ; char c2; //字符数据的运算及输出 c2=c1+32; cout>c1>>c2; cout //包含iostream.h头文件 main(){ char c1= \a ,TAB= \t ; //阵铃一声 cout //包含iostream.h头文件 main(){ //声明bool变量,并初始化 boolflag1=false,flag2=true; //输出布尔常量和变量 cout0; //存放关系运算结果 cout const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){ //声明3个变量 double r,l,s; //输入圆的半径 cout>r; //计算圆的周长 l=2*PI*r; cout main(){ //定义枚举类型,并指定其枚举元素的值 enum color { RED=3, YELLOW=6, BLUE=9 }; //声明枚举变量a和b,并为枚举变量a赋初值 enum color a=RED; color b; //合法,与C语言不同 // 输出枚举常量 cout const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){ //声明3个变量 double r=3,l,s; //计算圆的周长l=2*PI*r; cout main(){ //变量声明 char c; double x,y; //测试自增 cout main(){ int a=3, b=2; //输出关系表达式 coutb)=b)main(){ float a=3.5,b=2.1,c=0; cout=0 //显示a,b,c的值 cout main(){ //用 sizeof 计算各类种常量的字节长度 cout main(){ //声明变量语句中使用顺序运算 int x, y; //计算中使用顺序运算 x=50; y=(x=x-5, x/5); cout main(){ //测试表达式类型的转换 int n=100,m; double x=3.791,y; cout main(){ float a,b,s; cout>a>>b; //利用cin从键盘上为变量a,b 赋值 s=a; if (a main(){ int x,y; cout>x; if (x main(){ int a,b,c; int smallest; cout>a>>b>>c; if (a main() { int score; //从键盘上输入分数 cout>score; //用带else if的条件语句判断处理 if (score100){ cout=90)cout=80)cout=70)cout=60)cout main(){ int n; cout>n; if (n>=0 //输入数据 cout>a; cout>b; //找出较大值 Max=a>b?a:b; cout main(){ int a,b; //输入数据 cout>a; cout>b; //除法判断 if (b!=0 char c1; cin>>x>>c1>>y; //c1。
------------------------------------------------------------------------摘自宋鲁生程序设计大赛乘法口诀表#include <stdio.h>#include <conio.h>void main(void){int i,j,x,y;clrscr();printf("\n\n * * * 乘法口诀表* * * \n\n");x=9;y=5;for(i=1;i<=9;i++){gotoxy(x,y);printf("%2d ",i);x+=3;}x=7;y=6;for(i=1;i<=9;i++){gotoxy(x,y);printf("%2d ",i);y++;}x=9;y= 6;for(i=1;i<=9;i++){for(j=1;j<=9;j++){gotoxy(x,y);printf("%2d ",i*j);y++;}y-=9;x+=3;}printf("\n\n");}用一维数组统计学生成绩#include <stdio.h>void main(){char SelectKey,CreditMoney,DebitMoney;while(1){do{clrscr();puts("=========================");puts("| Please select key: |");puts("| 1. Quary |");puts("| 2. Credit |");puts("| 3. Debit |");puts("| 4. Return |");puts("=========================");SelectKey = getch();}while( SelectKey!='1' && SelectKey!='2' && SelectKey!='3' &&SelectKey!='4' );switch(SelectKey){case '1':clrscr();puts("================================");puts("| Your balance is $1000. |");puts("| Press any key to return... |");puts("================================");getch();break;case '2':do{clrscr();puts("==================================");puts("| Please select Credit money: |");puts("| 1. $50 |");puts("| 2. $100 |");puts("| 3. Return |");puts("==================================");CreditMoney = getch();}while( CreditMoney!='1' && CreditMoney!='2' && CreditMoney!='3' );switch(CreditMoney){case '1':clrscr();puts("=========================================");puts("| Your Credit money is $50,Thank you! |");puts("| Press any key to return... |");puts("=========================================");getch();break;case '2':clrscr();puts("==========================================");puts("| Your Credit money is $100,Thank you! |");puts("| Press any key to return... |");puts("==========================================");getch();break;case '3':break;}break;case '3':do{clrscr();puts("====================================");puts("| Please select Debit money: |");puts("| 1. $50 |");puts("| 2. $100 |");puts("| 3. $500 |");puts("| 4. $1000 |");puts("| 5. Return |");puts("====================================");DebitMoney = getch();}while( DebitMoney!='1' && DebitMoney!='2' && DebitMoney!='3' &&DebitMoney!='4' && DebitMoney!='5' );switch(DebitMoney){case '1':clrscr();puts("===========================================");puts("| Your Debit money is $50,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '2':clrscr();puts("===========================================");puts("| Your Debit money is $100,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '3':clrscr();puts("===========================================");puts("| Your Debit money is $500,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '4':clrscr();puts("===========================================");puts("| Your Debit money is $1000,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '5':break;}break;case '4':clrscr();puts("================================");puts("| Thank you for your using! |");puts("| Good bye! |");puts("================================");return;}}模拟ATM(自动柜员机)界面#include <stdio.h> void main(){int Password=0,Number=0,price=58,i=0;while( Password != 1234 ){if( i >= 3 )return;i++;puts("Please input Password: ");scanf("%d",&Password);}i=0;while( Number!=price ){do{puts("Please input a number between 1 and 100: ");scanf("%d",&Number);printf("Your input number is %d\n",Number);}while( !(Number>=1 && Number<=100) );if( Number >= 90 ){printf("Too Bigger! Press any key to try again!\n");}else if( Number >= 70 && Number < 90 ){printf("Bigger!\n");}else if( Number >= 1 && Number <= 30 ){printf("Too Small! Press any key to try again!\n");}else if( Number > 30 && Number <= 50 ){printf("Small! Press any key to try again!\n");}else{if( Number == price ){printf("OK! You are right! Bye Bye!\n");}else if( Number < price ){printf("Sorry,Only a little smaller! Press any key to try again!\n");}else if( Number > price ){printf(" Sorry, Only a little bigger! Press any key to try again!\n");}getch();}}用二维数组实现矩阵转置/* 用二维数组实现矩阵的转置*/#include <stdio.h>#define ROW 3#define COL 4main(){int matrixA[ROW][COL],matrixB[COL][ROW];int i,j; clrscr();printf("Enter elements of the matrixA,");printf("%d*%d:\n",ROW,COL);for( i=0; i<ROW; i++ ){for( j=0; j<COL; j++ ){scanf("%d",&matrixA[i][j]);}}for( i=0; i<ROW; i++ ){for( j=0; j<COL; j++ ){matrixB[j][i] = matrixA[i][j];}}printf("MatrixB,");printf("%d*%d:\n",COL,ROW);for( i=0; i<COL; i++ ){for( j=0; j<ROW; j++ ){printf("%8d",matrixB[i][j]);}printf("\n");}printf("\n Press Any Key to Quit... \n");getch();}求解二维数组的最大/最小元素#define MAXN 20int a[MAXN][MAXN];main(){int min, /* 存储最小值*/max; /* 存储最大值*/int row,col,n;clrscr();printf("Please input the order of the matrix:\n");/* 输入方阵的阶次*/ scanf("%d",&n);printf("Please input the elements of the matrix,\n from a[0][0] to a[%d][%d]:\n",n-1,n-1);for(row=0;row<n;row++)for(col=0;col<n;col++)scanf("%d",&a[row][col]);for(min=a[0][0],row=0;row<n;row++){/* 从每行选出最大数*/for(max=a[row][0],col=1;col<n;col++)/*从row行选出最大数*/if(max<a[row][col])max=a[row][col];if(min>max)/* 保存至row行的最小数*/min=max;}printf("The minimum of maximum number is %d\n",min);for(max=a[0][0],row=0;row<n;row++){/* 每行选出最小数*/for(min=a[row][0],col=1;col<n;col++)/* 从row行选出最小数*/ if(min>a[row][col])min=a[row][col];if(max<min)/*保存至row行的最大数*/max=min;}printf("The maximum of minimum numbers is %d\n",max);printf("\nPress any key to quit...\n");getch();}利用数组求前n个质数#define N 50main(){int primes[N];int pc,m,k; clrscr();printf("\n The first %d prime numbers are:\n",N);primes[0]=2;/*2是第一个质数*/pc =1;/*已有第一个质数*/m =3;/*被测试的数从3开始*/while(pc<N){/*调整m使它为下一个质数*/k=0;while(primes[k]*primes[k]<=m)if(m%primes[k]==0){/*m是合数*/m+=2;/*让m取下一个奇数*/k=1;/*不必用primes[0]=2去测试m,所以k从一开始*/}elsek++;/*继续用下一个质数去测试*/primes[pc++]=m;m+=2;/*除2外,其余质数均是奇数*/}/*输出primes[0]至primes[pc-1]*/for(k=0;k<pc;k++)printf("%4d",primes[k]);printf("\n\n Press any key to quit...\n ");getch();}编制万年历#include "stdio.h"long int f(int year,int month){/*f(年,月)=年-1,如月<3;否则,f(年,月)=年*/if(month<3) return year-1;else return year;} long int g(int month){/*g(月)=月+13,如月<3;否则,g(月)=月+1*/if(month<3) return month+13;else return month+1;} long int n(int year,int month,int day){/*N=1461*f(年、月)/4+153*g(月)/5+日*/return 1461L*f(year,month)/4+153L*g(month)/5+day;} int w(int year,int month,int day){/*w=(N-621049)%7(0<=w<7)*/return(int)((n(year,month,day)%7-621049L%7+7)%7);} int date[12][6][7];int day_tbl[ ][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};main(){int sw,leap,i,j,k,wd,day;int year;/*年*/char title[]="SUN MON TUE WED THU FRI SAT";clrscr();printf("Please input the year whose calendar you want to know: ");/*输入年*/scanf("%d%*c",&year);/*输入年份值和掠过值后的回车*/sw=w(year,1,1);leap=year%4==0&&year%100||year%400==0;/*判闰年*/for(i=0;i<12;i++)for(j=0;j<6;j++)for(k=0;k<7;k++)date[i][j][k]=0;/*日期表置0*/for(i=0;i<12;i++)/*一年十二个月*/for(wd=0,day=1;day<=day_tbl[leap][i];day++){/*将第i+1月的日期填入日期表*/date[i][wd][sw]=day;sw=++sw%7;/*每星期七天,以0至6计数*/if(sw==0) wd++;/*日期表每七天一行,星期天开始新的一行*/} printf("\n|==================The Calendar of Year %d=====================|\n|",year);for(i=0;i<6;i++){/*先测算第i+1月和第i+7月的最大星期数*/for(wd=0,k=0;k<7;k++)/*日期表的第六行有日期,则wd!=0*/wd+=date[i][5][k]+date[i+6][5][k];wd=wd?6:5;printf("%2d %s %2d %s |\n|",i+1,title,i+7,title);for(j=0;j<wd;j++){printf(" ");/*输出四个空白符*//*左栏为第i+1月,右栏为第i+7月*/for(k=0;k<7;k++)if(date[i][j][k])printf("%4d",date[i][j][k]);else printf(" ");printf(" ");/*输出十个空白符*/for(k=0;k<7;k++)if(date[i+6][j][k])printf("%4d",date[i+6][j][k]);else printf(" ");printf(" |\n|");}/*scanf("%*c");/*键入回车输出下一个月的日历*/}puts("=================================================================|") ;puts("\n Press any key to quit...");getch();}对数组元素排序rest(int a[], int n){int i,low,high,t; for(i=0,low=0,high=n-1;i<=high;) {if(a[i]>0){/*a[i]与a[high]交换,随之high减1*/t=a[i];a[i]=a[high];a[high]=t;high--;}else if(a[i]==0)i++; /* 掠过该元素*/else{/*a[i]与a[low]交换,随之low增1, i增1*/t=a[i];a[i]=a[low];a[low]=t;low++;i++;}}}int s[]={8,4,0,-1,6,0,-5};main(){int i;clrscr();printf("\n The arry before rest is:\n");for(i=0;i<sizeof(s)/sizeof(s[0]);i++)printf("%4d",s[i]);rest(s,sizeof(s)/sizeof(s[0]));printf("\n The arry after rest is:\n");for(i=0;i<sizeof(s)/sizeof(s[0]);i++)printf("%4d",s[i]);printf("\n Press any key to quit...\n");getch();}任意进制数的转换/* 函数trans将无符号整数n翻译成d(2<=d<=16)进制表示的字符串s */ #define M sizeof(unsigned int)*8int trans(unsigned n, int d, char s[]){static char digits[] ="0123456789ABCDEF"; /* 十六进制数字的字符*/char buf[M+1];int j, i = M;if(d<2||d>16){s[0]='\0'; /* 不合理的进制,置s为空字符串*/return 0; /* 不合理的进制,函数返回0 */}buf[i]='\0';do{buf[--i]=digits[n%d]; /*译出最低位,对应字符存入对应工作数组中*/n/=d;}while(n);/* 将译出在工作数组中的字符串复制到s */for(j=0;(s[j]=buf[i])!='\0';j++,i++);/* 其中控制条件可简写成s[j]=buf[i] */return j;}/* 主函数用于测试函数trans() */main(){unsigned int num = 253;int scale[]={2,3,10,16,1};char str[33];int i;clrscr();for(i=0;i<sizeof(scale)/sizeof(scale[0]);i++){if(trans(num,scale[i],str))printf("%5d = %s(%d)\n",num,str,scale[i]);elseprintf("%5d => (%d) Error! \n",num,scale[i]);}printf("\n Press any key to quit...\n");getch();}判断回文数/* 函数circle用于判断正整数n的d进制数表示形式是否是回文数*/ int circle(int n, int d){int s=0,m=n;while(m){s=s*d+m%d;m/=d;}return s==n;}/* main函数用于测试circle函数*/int num[]={232,27,851};int scale[]={2,10,16};main(){int i,j;clrscr();for(i=0;i<sizeof(num)/sizeof(num[0]);i++)for(j=0;j<sizeof(scale)/sizeof(scale[0]);j++)if(circle(num[i],scale[j]))printf("%d -> (%d) is a Circle Number!\n",num[i],scale[j]);elseprintf("%d -> (%d) is not a Circle Number!\n",num[i],scale[j]);printf("\n Press any key to quit...\n");getch();}求解钢材切割的最佳订单#include <stdio.h>#define N 20#define DELTA 2int bestlen;int bestsele[N];int sele[N];int n;int orderlen[N];int total;main(){int i;clrscr();printf("\n Please enter total length of the steel:\n");/* 输入钢材总长*/scanf("%d",&total);printf("\n Please enter number of order:\n"); /* 输入定单数*/ scanf("%d",&n);printf("\n Please enter the orders:\n"); /* 输入各定单*/for(i=0;i<n;i++)scanf("%d",&orderlen[i]);bestlen=0; /*最佳解用料的初值*/for(i=0;i<n;i++)sele[i]=bestsele[i]=0; /*置当前选择和最佳选择初值*/try(); /* 调用函数求解*/for(i=0;i<n;i++) /* 输出结果*/if(bestsele[i])printf("order %d length = %d\n",i+1,orderlen[i]);printf("\n Press any key to quit...");getch();}try(){int i,len;for(len=i=0;i<n;i++) /* 求当前选中的用料量*/if(sele[i])len+=orderlen[i]+DELTA;if(len-DELTA<=total) /* 注意最后一段可能不需要切割*/{if(bestlen < len){/* 找到一个更好的解*/bestlen = len;for(i=0;i<n;i++)bestsele[i]=sele[i];}for(i=0;i<n;i++) /* 对所有未选定单逐一作选中尝试循环*/if(!sele[i]){sele[i]=1; /* 做选中尝试*/try();sele[i]=0;}}}指向数组的指针main(){int x,y,z; /* 定义三个int型变量*/int *xp = &x, /* 定义指针变量xp,并赋值为x的地址,使xp指向x */ *yp = &y, /* 定义指针变量yp,并赋值为y的地址,使yp指向y */*zp = &z; /* 定义指针变量zp,并赋值为z的地址,使zp指向z */int t;printf("\nPlease input x,y,z:\n");scanf("%d%d%d",xp,yp,zp); /* 通过变量的指针,为变量输入值*/ if(*xp>*yp) /* 通过指向变量的指针引用变量的值*/{t=*xp; /* 通过指向变量的指针引用变量的值*/*xp=*yp;/* 通过指向变量x的指针xp,引用变量x的值*/*yp=t; /* 通过指向变量y的指针yp,引用变量y的值*/}if(*xp>*zp) /* 通过指向变量的指针,引用变量的值*/{t=*xp; /* 通过指向变量x的指针xp,引用变量x的值*/*xp=*zp;/* 通过指向变量x的指针xp,引用变量x的值*/*zp=t; /* 通过指向变量z的指针zp,引用变量z的值*/}if(*yp>*zp) /* 通过指向变量的指针,引用变量的值*/{t=*yp; /* 通过指向变量的指针,引用变量的值*/*yp=*zp;/* 通过指向变量y的指针yp,引用变量y的值*/*zp=t;/* 通过指向变量z的指针zp,引用变量z的值*/}printf("x = %d\ty = %d\tz = %d\n",x,y,z);printf("\nPress any key to quit...\n");getch();}阿拉伯数字转换为罗马数字#include <stdio.h>#define ROWS 4#define COLS 4int nums[ROWS][COLS]={{1000,1000,1000,1000},{900,500,400,100},{90,50,40,10},{9,5,4,1}};char *roms[ROWS][COLS]={{"m","m","m","m"}, {"cm","d","cd","c"},{"xc","l","xl","x"},{"ix","v","iv","i"}}; main(int argc,char *argv[ ]){int low,high;char roman[25]; if(argc<2){ printf("Usage:roman decimal_number\n");/*运行程序需带整数参数*/}high=low=atoi(argv[1]);/*将第一个参数转换成整数*/checknum(low);if(argc>2){/*带两个参数*/high=atoi(argv[2]);checknum(high);if(low>high){low=high;high=atoi(argv[1]);}}elselow=1;for(;low<=high;low++){to_roman(low,roman);printf("%d\t%s\n",low,roman);}} checknum(int val)/*检查参数合理性*/{if(val<1||val>9999){printf("The number must be in range 1..9999.\n");exit(0);}}to_roman(int decimal,char roman[ ])/*将整数转换成罗马数字表示*/ {int power,index;roman[0]='\0';for(power=0;power<ROWS;power++)for(index=0;index<COLS;index++)while(decimal>=nums[power][index]){strcat(roman,roms[power][index]);decimal-=nums[power][index];}}通讯录的输入输出#include <stdio.h>#define ZIPLEN 10#define PHONLEN 15/*struct addr类型定义*/ struct addr{char *name;/*姓名*/char *address;/*地址*/char zip[ZIPLEN];/*邮政编码*/char phone[PHONLEN];/*电话号码*/}; main()/*本主函数示意上述输入输出函数的用法*/{struct addr p[100];int i,j;clrscr();for(i=0;readaddr(p+i);i++);for(j=0;j<i;j++) writeaddr(p+j);puts("\n Press any key to quit...");getch();} /* 函数readaddr用于输入一个通信录函数*/int readaddr(struct addr *dpt){int len;char buf[120];/*输入字符串的缓冲区*/ printf("\nPlease input theName:\n");/*输入姓名*/if(scanf("%s",buf)==1){len=strlen(buf);dpt->name=(char *)malloc(len+1);/*申请存贮姓名的空间*/ strcpy(dpt->name,buf);}else return 0;/*Ctrl+Z结束输入*/printf("Please input the Address:\n");/*输入地址*/if(scanf("%s",buf)==1){len=strlen(buf);dpt->address=(char *)malloc(len+1);/*申请存贮地址的空间*/ strcpy(dpt->address,buf);}else{/*Ctrl+Z结束输入*/free(dpt->name);/*释放存贮姓名的空间*/return 0;}printf("Please input the Zip code:\n");/*输入邮编*/if(scanf("%s",buf)==1)strncpy(dpt->zip,buf,ZIPLEN-1);else{free(dpt->name);/*释放存贮姓名的空间*/free(dpt->address);/*释放存贮地址的空间*/return 0;/*Ctrl+Z结束输入*/}printf("Please input the Phone number:\n");/*输入电话号码*/ if(scanf("%s",buf)==1)strncpy(dpt->phone,buf,PHONLEN-1);else{free(dpt->name);free(dpt->address);return 0;/*Ctrl+Z结束输入*/}return 1;} /* 函数writeaddr用于输出通讯录*/int writeaddr(struct addr*dpt){printf("Name : %s\n", dpt->name);/*输出姓名*/printf("Address : %s\n", dpt->address);/*输出地址*/printf("Zip : %s\n", dpt->zip);/*输出邮编*/printf("Phone : %s\n\n", dpt->phone);/*输出电话号码*/}扑克牌的结构表示enum suits{CLUBS,DIAMONDS,HEARTS,SPADES}; struct card{enum suits suit;char value[3];};struct card deck[52];char cardval[][3]= {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};char suitsname[][9]={"CLUBS","DIAMONDS","HEARTS","SPADES"}; main() {int i,j;enum suits s;clrscr();for(i=0;i<=12;i++)for(s=CLUBS;s<=SPADES;s++){j=i*4+s;deck[j].suit=s;strcpy(deck[j].value,cardval[i]);}for(j=0;j<52;j++)printf("(%s%3s)%c",suitsname[deck[j].suit],deck[j].value,j%4==3?'\n':'\t');puts("\nPress any key to quit...");getch();}用“结构”统计学生成绩#include <stdio.h>#define N 200#define SCORES 5#define NUMLEN 10struct std_type{char no[NUMLEN];/*学号*/char *name;/*名字符串指针*/int scores[SCORES];/*五门功课的成绩*/};struct std_type students[N];int order[N];int total[N]; /*[函数]输入一个学生信息函数*/int readastu(struct std_type *spt){int len,j;char buf[120];/*输入字符串的缓冲区*/ printf("\nNumber : ");/*输入学号*/if(scanf("%s",buf)==1)strncpy(spt->no,buf,NUMLEN-1);elsereturn 0;/*Ctrl+Z结束输入*/printf("Name : ");/*输入姓名*/if(scanf("%s",buf)==1){len=strlen(buf);spt->name=(char *)malloc(len+1);/*申请存贮姓名的空间*/ strcpy(spt->name,buf);}else return 0;/*Ctrl+Z结束输入*/printf("Scores : ");/*输入成绩*/for(j=0;j<SCORES;j++)if(scanf("%d",spt->scores+j)!=1)break;if(j==0)/*一个成绩也未输入*/{free(spt->name);/*释放存贮姓名的空间*/return 0;}for(;j<SCORES;j++)/*少数未输入的成绩用0分代之*/ spt->scores[j]=0;return 1;} /*[函数]输出一个学生信息的函数*/int writeastu(struct std_type *spt){int i; printf("Number : %s\n",spt->no);/*输出学号*/printf("Name : %s\n",spt->name);/*输出姓名*/printf("Scores : ");/*输出成绩*/for(i=0;i<SCORES;i++)printf("%4d",spt->scores[i]);printf("\n\n");} main(){int n,i,j,t; clrscr();for(n=0;readastu(students+n);n++);/*采用冒泡法对学生信息数组排序*/for(i=0;i<n;i++){order[i]=i;/*预置第i个输入的学生*/for(t=0,j=0;j<SCORES;j++)/*求第i个学生的总分*/t+=students[i].scores[j];total[i]=t;}/*冒泡排序*/for(i=0;i<n-1;i++)/*共扫视n-1遍*/for(j=0;j<n-1-i;j++)if(total[order[j]]<total[order[j+1]]){/*交换名次*/t=order[j];order[j]=order[j+1];order[j+1]=t;}for(j=0;j<n;j++)/*输出*/writeastu(students+order[j]);printf("\n Press any key to quit...\n");getch();}报数游戏#include <stdio.h>struct ele{int no;struct ele *link;}main(){int n,m,i;struct ele *h,*u,*p;clrscr();printf("Please input n&m:\n");scanf("%d%d",&n,&m);/*输入n和m*/h=u=(struct ele *)malloc(sizeof(struct ele));/*形成首表元*/ h->no=1;for(i=2;i<=n;i++)/*形成其余的n-1个表元*/{u->link=(struct ele *)malloc(sizeof(struct ele));u=u->link;u->no=i;/*第i个表元置编号i*/}u->link=h;/*末表元后继首表元,形成环*/puts("\nThe numbers of who will quit the cycle in turn are:"); while(n){for(i=1;i<m;i++)/*掠过m-1个表元*/u=u->link;p=u->link;/*p指向第m个表元*/u->link=p->link;/*第m个表元从环中脱钩*/printf("%4d",p->no);free(p);/*释放第m个表元占用的空间*/n--;}printf("\n\n Press any key to quit...\n");getch();}学生成绩管理程序/*学生成绩管理程序编制一个统计学生考试分数的管理程序。
#include<graphics.h>#include<conio.h>#include<string.h>#include<bios.h>#include<stdlib.h>#include"c:\tc\LIB\1.c"#define W 119#define S 115#define A 97#define D 100#define space 32#define UP 72#define DOWN 80#define LEFT 75#define RIGHT 77#define ENTER 13void qipan();void jiemian(int);void guangbiao1(int,int);void guangbiao2(int,int);void xuanzhong(int,int);void gaizi(int,int);char array(int,int);void xiazi(int,int,int,int);/*int panding(char,int,int,int,int);*/main(){int gdriver,gmode,i=0,c=0,x=190,y=190,m,n; char p;FILE *fp;gdriver=DETECT;gmode=0;if((fp=fopen("file.txt","at")) == NULL) {printf("Cannot open file!");system("pause");exit(0);}printf("%d,%d",gdriver,gmode); registerbgidriver(EGAVGA_driver);initgraph(&gdriver,&gmode,"c:\\tc"); cleardevice();while(c!=27){c=getch();clrscr();jiemian(i);if(c==80){fputs("down ",fp);i++;if(i==4){i=0;}}if(i==1){if(c==13){fputs("enter ",fp);qipan();c=getch();while(c!=27){c=getch();if(c==115){fputs("S ",fp);y=y+40;guangbiao1(x,y);guangbiao2(x,y-40);}if(c==119){fputs("W ",fp);y=y-40;guangbiao1(x,y);guangbiao2(x,y+40);}if(c==97){ fputs("A\n",fp);x=x-40;guangbiao1(x,y);guangbiao2(x+40,y);}if(c==100){ fputs("D\n",fp);x=x+40;guangbiao1(x,y);guangbiao2(x-40,y);}if(c==13){fputs("enter\n",fp);xuanzhong(x,y);m=x;n=y;}if(c==32){fputs("space\n",fp);xiazi(m,n,x,y);fputs("gaizi\n",fp);gaizi(m,n);}if(x>350||y>390||x<30||y<30){x=190;y=30;}}}}}getch();closegraph();fclose(fp);restorecrtmode();return 0;}void qipan(){int i,j;setbkcolor(GREEN);cleardevice();setlinestyle(0,0,3);setcolor(1);rectangle(10,10,370,410);rectangle(30,30,350,390);for(i=1;i<8;i++){setlinestyle(0,0,3);line(i*40+30,30,i*40+30,190);line(i*40+30,230,i*40+30,390);}for(j=1;j<9;j++){setlinestyle(0,0,3);line(30,j*40+30,350,j*40+30);}setlinestyle(3,0,3);line(150,30,230,110);line(230,30,150,110);line(150,310,230,390);line(230,310,150,390); setusercharsize(4,1,2,1); settextstyle(1,0,4);outtextxy(70,195,"chinese chess"); red_shuai(190,30);red_shi(150,30);red_shi(230,30);red_xiang(110,30);red_xiang(270,30);red_ma(70,30);red_ma(310,30);red_ju(30,30);red_ju(350,30);red_pao(70,110);red_pao(310,110);red_bing(30,150);red_bing(110,150);red_bing(190,150);red_bing(270,150);red_bing(350,150);black_jiang(190,390);black_shi(150,390);black_shi(230,390);black_xiang(110,390);black_xiang(270,390);black_ma(70,390);black_ma(310,390);black_ju(30,390);black_ju(350,390);black_pao(70,310);black_pao(310,310);black_zu(30,270);black_zu(110,270);black_zu(190,270);black_zu(270,270);black_zu(350,270);setcolor(BLUE);rectangle(400,30,600,320);setcolor(4);settextstyle(1,0,2);outtextxy(420,50,"A->shuai B->shi"); outtextxy(420,80,"C->xiang D->ma"); outtextxy(420,110,"E->ju F->pao"); outtextxy(420,140,"G->bing"); setcolor(8);outtextxy(420,200,"H->jiang I->shi"); outtextxy(420,230,"J->xiang K->ma"); outtextxy(420,260,"L->ju M->pao"); outtextxy(420,290,"N->zu");}void jiemian(int i){setbkcolor(GREEN); cleardevice();settextstyle(1,0,8);setcolor(BLUE);outtextxy(50,70,"chinese chess"); settextstyle(0,0,3);setcolor(RED);outtextxy(260,215,"start"); outtextxy(260,255,"again"); outtextxy(260,295,"undo"); outtextxy(260,335,"exit"); rectangle(250,210+i*40,390,240+i*40); }void guangbiao1(int x,int y){setcolor(WHITE);setlinestyle(0,0,3);line(x-17,y-7,x-17,y-17);line(x-7,y-17,x-17,y-17);line(x+7,y-17,x+17,y-17);line(x+17,y-7,x+17,y-17);line(x-7,y+17,x-17,y+17);line(x-17,y+7,x-17,y+17);line(x+17,y+7,x+17,y+17);line(x+7,y+17,x+17,y+17);}void guangbiao2(int x,int y){setcolor(GREEN);setlinestyle(0,0,3);line(x-17,y-7,x-17,y-17);line(x-7,y-17,x-17,y-17);line(x+7,y-17,x+17,y-17);line(x+17,y-7,x+17,y-17);line(x-7,y+17,x-17,y+17);line(x-17,y+7,x-17,y+17);line(x+17,y+7,x+17,y+17);line(x+7,y+17,x+17,y+17);}void xuanzhong(int x,int y){setcolor(CYAN);setlinestyle(0,0,3);circle(x,y,15);}void gaizi(int x1,int y1){setlinestyle(0,0,3);setcolor(GREEN);circle(x1,y1,15);setfillstyle(0,3);floodfill(x1,y1,GREEN);setcolor(1);setlinestyle(0,0,3);if((30<x1<350)&&((y1==30)||(y1==230))) {line(x1-18,y1,x1+18,y1);line(x1,y1,x1,y1+18);if((30<x1<350)&&(y1==390||y1==190)) {line(x1-18,y1,x1+18,y1);line(x1,y1-18,x1,y1);}if((30<y1<390)&&x1==30){line(x1,y1,x1+18,y1);line(x1,y1-18,x1,y1+18);}if((30<y1<390)&&(x1==350)){line(x1-18,y1,x1,y1);line(x1,y1-18,x1,y1+18);}if((x1==30)&&(y1==30)){line(x1,y1,x1+18,y1);line(x1,y1,x1,y1+18);}if((x1==350)&&(y1==30)){line(x1-18,y1,x1,y1);line(x1,y1,x1,y1+18);}if((x1==30)&&(y1==390)){line(x1,y1,x1+18,y1);line(x1,y1,x1,y1-18);}if((x1==350)&&(y1==390)){line(x1,y1,x1-18,y1);line(x1,y1,x1,y1-18);}else{line(x1-18,y1,x1+18,y1);line(x1,y1-18,x1,y1+18);}}char array(int i,int j)char a[13][13];int c,b;c=i;b=j;for(c=1;c<10;c++){for(b=1;b<11;b++){a[c][b]='Z';}}a[1][5]='A';a[1][4]='B';a[1][6]='B';a[1][3]='C';a[1][7]='C';a[1][2]='D';a[1][8]='D';a[1][1]='E';a[1][9]='E';a[3][2]='F';a[3][8]='F';a[4][1]=a[4][3]=a[4][5]=a[4][7]=a[4][9]='G';a[10][5]='H';a[10][4]='I';a[10][6]='I';a[10][3]='J';a[10][7]='J';a[10][2]='K';a[10][8]='K';a[10][1]='L';a[10][ 9]='L';a[2][3]='M';a[8][3]='M';a[7][1]=a[7][3]=a[7][5]=a[7][7]=a[7][9]='N';return a[i][j];}void xiazi(int x6,int y6,int x7,int y7){switch(array(y6/40+1,x6/40+1)){case 'A':red_shuai(x7,y7);break;case 'B':red_shi(x6,y7);break;case 'C':red_xiang(x7,y7);break;case 'D':red_ma(x7,y7);break;case 'E':red_ju(x7,y7);break;case 'F':red_pao(x7,y7);break;case 'G':red_bing(x7,y7);break;case 'H':black_jiang(x7,y7);break;case 'I':black_shi(x7,y7);break;case 'J':black_xiang(x7,y7);break;case 'K':black_ma(x7,y7);break;case 'L':black_ju(x7,y7);break;case 'M':black_pao(x7,y7);break;case 'N':black_zu(x7,y7);break;case 'Z':gaizi(x6,x6);break;}}/*int panding(char q,int x,int y,int a,int b){switch(q){case 'A':if(y>110||x>230||x<150||(a-x)>40||(x-a)>40||(y-b)>40||(b-y)>40)return 0;elsereturn 1;break;case'B':if(((x-a)==40&&(y-b)==40)&&y<=110&&230<x<150||((a-x)==40&&(b-y)==40)&&y<=110& &230>x>150)return 1;elsereturn 0;break;case'C':if((((x-a)==80&&(y-b)==80)&&y<=190)&&(array((y+b)/2/40+1,(x+a)/2/40+1,)=='Z')))||(((a-x)==80&&(b-y)==80)&&y<=190)&&(array((y+b)/2/40+1,(x+a)/2/40+1)=='Z'))))return 1;elsereturn 0;break;case'D':if((((x-a)==80&&(y-b)==40&&(array(y/40+1,(x-40)/40+1)=='Z'))||(((a-x)==80&&(b-y)==40)&&(array(y/40+1,(x+40)/40+1)=='Z'))||(((x-a)==40&&(y-b)==80)(array((y-40)/40+1,x/40+1)==' Z'))||(((a-x)==40&&(b-y)==80)&&(array((y+40)/40+1,x/40+1)=='z'))))return 1;elsereturn 0;break;case 'E':return 1;break;case 'F':return 1;break;case 'G':if(y<190){if(y>b||x!=a){return 0;}elsereturn 1;}else{if((b-y)>40||(a-x)>40||(x-a)>40||y>b){return 0;}elsereturn 1;}break;case 'H':if(y<310||x>230||x<150||(a-x)>40||(x-a)>40||(y-b)>40||(b-y)>40)return 0;elsereturn 1;break;case'I':if(((x-a)==40&&(y-b)==40)&&y>=310&&230<x<150||((a-x)==40&&(b-y)==40)&&y>310&& 230>x>150)return 1;elsereturn 0;break;case可编辑'J':if(((((x-a)==80&&(y-b)==80)&&y>=230)&&array(((y+b)/2/40+1,(x+a)/2/40+1)=='Z')))||(((a-x )==80&&(b-y)==80)&&y>=230)&&(array((y+b)/2/40+1,(x+a)/2/40+1)=='Z'))))return 1;elsereturn 0;break;case'K':if((((x-a)==80&&(y-b)==40&&(array(y/40+1,(x-40)/40+1)=='Z'))||(((a-x)==80&&(b-y)==40) &&(array(y/40+1,(x+40)/40+1)=='Z'))||(((x-a)==40&&(y-b)==80)(array((y-40)/40+1,x/40+1)==' Z'))||(((a-x)==40&&(b-y)==80)&&(array((y+40)/40+1,x/40+1)=='Z'))return 1;elsereturn 0;break;case 'L':return 1;break;case 'M':return 1;break;case 'N':if(y>230){if(y<b||x!=a){return 0;}elsereturn 1;}else{if(y-b>40||(a-x)>40||(x-a)>40||y<b){return 0;}elsereturn 1;}default:return 0;}}*/.。
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语言(C51)常用库函数单片机C语言(C51)常用库函数在单片机编程中,使用库函数可以大大提高开发效率和简化代码结构。
C51是一种常用的单片机编程语言,它提供了许多常用的库函数,本文将介绍一些常用的C51库函数及其用法。
1. 字符串处理函数字符串处理是单片机编程中常见的任务。
C51提供了一些常用的字符串处理函数,如strcpy、strcat、strcmp等。
这些函数可以简化对字符串的操作。
- strcpy:用于将一个字符串复制到另一个字符串中。
用法示例:```char str1[20];char str2[20] = "Hello, world!";strcpy(str1, str2);```- strcat:用于将一个字符串追加到另一个字符串的末尾。
用法示例:```char str1[20] = "Hello,";char str2[20] = " world!";strcat(str1, str2);```- strcmp:用于比较两个字符串是否相等。
用法示例:```char str1[20] = "Hello";char str2[20] = "World";if (strcmp(str1, str2) == 0) {// 字符串相等的处理逻辑} else {// 字符串不相等的处理逻辑}```2. 数学函数单片机编程中常常需要进行数学运算,C51提供了一些常用的数学函数,如abs、sqrt、sin等。
这些函数可以帮助实现各种数学计算。
- abs:用于计算一个整数的绝对值。
用法示例:```int num = -10;int abs_num = abs(num);```- sqrt:用于计算一个浮点数的平方根。
用法示例:```float x = 16.0;float sqrt_x = sqrt(x);```- sin:用于计算一个角度的正弦值。
c++基础程序代码(一)以下是一个简单的C++程序代码,用于输出“Hello, World!”:c#include <iostream>int main() {std::cout << "Hello, World!" << std::endl;return 0;}这个程序使用了C++标准库中的iostream库,通过std::cout输出“Hello, World!”,然后使用std::endl输出一个换行符。
最后,程序返回0表示正常退出。
c++基础程序代码(二)稍微复杂一点的C++程序示例,用于计算两个数的和:c#include <iostream>int main() {int num1, num2, sum;std::cout << "请输入第一个数:";std::cin >> num1;std::cout << "请输入第二个数:";std::cin >> num2;sum = num1 + num2;std::cout << "两个数的和为:" << sum << std::endl; return 0;}该程序首先声明了三个整数变量num1、num2和sum,然后使用std::cout对象输出提示信息,让用户输入第一个数和第二个数。
接着使用std::cin对象读取用户输入的两个数,并将它们相加存储到sum变量中。
最后使用std::cout对象输出计算结果。
c++基础程序代码(三)当然可以,以下是一个更复杂的C++程序示例,用于实现简单的计算器:c#include <iostream>int main() {int num1, num2;char op;std::cout << "请输入第一个数:";std::cin >> num1;std::cout << "请输入操作符:";std::cin >> op;std::cout << "请输入第二个数:";std::cin >> num2;switch (op) {case '+':std::cout << "结果是:" << num1 + num2 << std::endl;break;case '-':std::cout << "结果是:" << num1 - num2 << std::endl;break;case '*':std::cout << "结果是:" << num1 * num2 << std::endl;break;case '/':if (num2 == 0) {std::cout << "除数不能为0,请重新输入!" << std::endl;} else {std::cout << "结果是:" << num1 / num2 << std::endl;}break;default:std::cout << "不支持该操作符,请重新输入!" << std::endl;break;}return 0;}。
需要使用UGUISTYLER建立对话框和建立一个花键模板零件下面分别是主要程序代码/*==================================================================== =========W ARNING!! This file is overwritten by the UIStyler each time the Stylerfile is saved.Filename: spline_dialog_template.cThis file was generated by the NX User Interface StylerCreated by: HaoVersion: NX 4Date: 06-04-11Time: 22:26This template file is overwritten each time the UIStyler dialog issaved. Any modifications to this file will be lost.====================================================================== ========*//*==================================================================== ==========Purpose: This TEMPLATE file contains C source and static structures toguide you in the construction of your NX Open application dialog.The generation of your dialog file (.dlg extension) is the first step towardsdialog construction within Unigraphics. You must now create a UGOpenapplication that utilizes this file (.dlg).The information in this file provides you with the following:1. Help on the use of the functions, UF_MB_add_styler_actions andUF_STYLER_create_dialog in your NX Open application. These functionswill load and display your UIStyler dialog in Unigraphics.An example of the function, UF_MB_add_styler_actions to associate yourdialog to the menubar is shown below (Search on Example 1).An example of a invoking a dialog from a callback utilizingUF_STYLER_create_dialog is also shown below (Search for Example 2).An example of a user exit utilizing UF_STYLER_create_dialog is alsoshown below (Search for Example 3).2. The callback structure: --- CHANGE_cbs ---This structure is VERY important if you have callbacks associated withyour dialog. It correlates the dialog items in your dialog with thecallback functions you must supply. You should not modify thisstructure since it MUST match up to the information stored in yourdialog file (.dlg). Any attempt to do so will cause an error whileconstructing your dialog. If you wish to modify the association ofyour callbacks to your dialog, please reload your dialog file (.dlg) intothe UIStyler and regenerate your files.You do not need to be concerned about this structure, simply pass it asan argument to the function, UF_STYLER_create_dialog along with yourdialog file (.dlg).Example 1 displays the actual call you may make for this particulardialog.3. The empty callback functions (stubs) associated with your dialog itemshave also been placed in this file. These empty functions have beencreated simply to start you along with your coding requirements.The function name, argument list and possible return values have alreadybeen provided for you.NOTE: Each callback must be wrappered with the functions UF_initialize()and UF_terminate().====================================================================== ========*//* These include files are needed for the following template code. */#include <stdio.h>#include <uf.h>#include <uf_defs.h>#include <uf_exit.h>#include <uf_ui.h>#include <uf_styler.h>#include <uf_mb.h>#include <stdlib.h>#include <uf_modl_expressions.h>#include <uf_part.h>#include <uf_modl.h>#include "spline_dialog.h"/* The following definition defines the number of callback entries *//* in the callback structure: *//* UF_STYLER_callback_info_t CHANGE_cbs */#define SPLINE_CB_COUNT ( 4 + 1 ) /* Add 1 for the terminator *//*--------------------------------------------------------------------------The following structure defines the callback entries used by thestyler file. This structure MUST be passed into the user function,UF_STYLER_create_dialog along with CHANGE_CB_COUNT.--------------------------------------------------------------------------*/static UF_STYLER_callback_info_t SPLINE_cbs[SPLINE_CB_COUNT] ={{UF_STYLER_DIALOG_INDEX, UF_STYLER_CONSTRUCTOR_CB , 0, SPLINE_constructor},{UF_STYLER_DIALOG_INDEX, UF_STYLER_DESTRUCTOR_CB , 0, SPLINE_destructor},{UF_STYLER_DIALOG_INDEX, UF_STYLER_OK_CB , 0, SPLINE_ok}, {UF_STYLER_DIALOG_INDEX, UF_STYLER_CANCEL_CB , 0, SPLINE_cancel}, {UF_STYLER_NULL_OBJECT, UF_STYLER_NO_CB, 0, 0 }};/*--------------------------------------------------------------------------UF_MB_styler_actions_t contains 4 fields. These are defined as follows:Field 1 : the name of your dialog that you wish to display.Field 2 : any client data you wish to pass to your callbacks.Field 3 : your callback structure.Field 4 : flag to inform menubar of your dialog location. This flag MUSTmatch the resource set in your dialog! Do NOT ASSUME that changingthis field will update the location of your dialog. Please use theUIStyler to indicate the position of your dialog.--------------------------------------------------------------------------*/static UF_MB_styler_actions_t actions[] = {{ "spline_dialog.dlg", NULL, SPLINE_cbs, UF_MB_STYLER_IS_NOT_TOP },{ NULL, NULL, NULL, 0 } /* This is a NULL terminated list */};/*---------------- MENUBAR HOOKUP HELP Example -------------------To launch this dialog from a Unigraphics menubar, you must followthe steps below.1) Add the following lines to your MenuScript file in order toassociate a menu bar button with your dialog. In thisexample, a cascade menu will be created and will belocated just before the Help button on the main menubar.The button, SPLINE_DIALOG_BTN is set up to launch your dialog andwill be positioned as the first button on your pulldown menu.If you wish to add the button to an existing cascade, simplyadd the 3 lines between MENU LAUNCH_CASCADE and END_OF_MENU to your menuscript file.The MenuScript file requires an extension of ".men".Make sure that you add the extension to the file and placethe file in your startup directory:$UGII_USER_DIR/startup or$UGII_SITE_DIR/startup or$UGII_VENDOR_DIR/startup directoryMove the contents between the dashed lines to your Menuscript file.! ----------------------------------------------------------------VERSION 120EDIT UG_GATEW AY_MAIN_MENUBARBEFORE UG_HELPCASCADE_BUTTON UISTYLER_DLG_CASCADE_BTNLABEL Dialog LauncherEND_OF_BEFOREMENU UISTYLER_DLG_CASCADE_BTNBUTTON SPLINE_DIALOG_BTNLABEL Display spline_dialog dialogACTIONS spline_dialog.dlgEND_OF_MENU! ---------------------------------------------------------------2) Issue a call to the function, UF_MB_add_styler_actions from the ufstauser exit as shown below. To use this call, remove the conditionaldefinitions: #ifdef MENUBAR_COMMENTED_OUT#endif MENUBAR_COMMENTED_OUTThe static structure, actions, will allow you to associate ALL of yourdialogs and callback functions to the menubar at once. For example, if you wish to have 10 dialogs associated to 10 different buttons on the menubar,you may enter each dialog and callback list into the actions structure. Make sure that you have created a corresponding button in your MenuScript file.You may also have separate shared libraries, each with a ufsta user exitfor each individual dialog.3) Place your compiled and linked ufsta user function in$UGII_USER_DIR/startup or$UGII_SITE_DIR/startup or$UGII_VENDOR_DIR/startup directory.NOTE: The user function must contain the proper extension .so, .sl or .dll to make ensure that it is recognized by the MenuScript. If it does nothave the proper extension, it will NOT be recognized by MenuScript.The action name you have provided in your MenuScript must correspond to to the dialog name provided in the action structure. This MUST match inorder to bind your dlg file to your MenuScript button.4) Copy your UIStyler dialog file to the proper directory.All dialog files (.dlg) must be located in$UGII_USER_DIR/application or$UGII_SITE_DIR/application or$UGII_VENDOR_DIR/application directory------------------------------------------------------------*///#ifdef MENUBAR_COMMENTED_OUTextern void ufsta (char *param, int *retcode, int rlen){int error_code;if ( (UF_initialize()) != 0)return;if ( (error_code = UF_MB_add_styler_actions ( actions ) ) != 0 ){char fail_message[133];UF_get_fail_message(error_code, fail_message);printf ( "%s\n", fail_message );}UF_terminate();return;}//#endif /*MENUBAR_COMMENTED_OUT*//*-------DIALOG CREATION FROM A CALLBACK HELP Example ---------- If you wish to have this dialog displayed from the callback ofanother UIStyler dialog, you should:1) Make sure that the callback of your UIStyler dialog isdesignated as a dialog building callback.2) Remove the conditional definitions:#ifdef DISPLAY_FROM_CALLBACK#endif DISPLAY_FROM_CALLBACK3) Your callback should issue a call to this function.4) You should also add the funcitonal prototype to your header file(spline_dialog.h) and ensure that the file is properly included.All dialog files must be located in$UGII_USER_DIR/application or$UGII_SITE_DIR/application or$UGII_VENDOR_DIR/application directory--------------------------------------------------------------*/#ifdef DISPLAY_FROM_CALLBACKextern int <enter the name of your function> ( int *response ){int error_code = 0;if ( ( error_code = UF_initialize() ) != 0 )return (0) ;if ( ( error_code = UF_STYLER_create_dialog ( "spline_dialog.dlg", CHANGE_cbs, /* Callbacks from dialog */CHANGE_CB_COUNT, /* number of callbacks*/NULL, /* This is your client data */response ) ) != 0 ){char fail_message[133];/* Get the user function fail message based on the fail code.*/UF_get_fail_message(error_code, fail_message);UF_UI_set_status (fail_message);printf ( "%s\n", fail_message );}UF_terminate();return (error_code);}#endif /* DISPLAY_FROM_CALLBACK *//*-------DIALOG CREATION FROM A USER EXIT HELP Example -------- To create this dialog from a user exit, you must invoke acall to the NX Open API, UF_STYLER_create_dialog. An exampleis shown below.All dialog files must be located in$UGII_USER_DIR/application or$UGII_SITE_DIR/application or$UGII_VENDOR_DIR/application directory1) Remove the conditional definitions:#ifdef DISPLAY_FROM_USER_EXIT#endif DISPLAY_FROM_USER_EXIT2) Add a user exit to the function name below, for example, ufusr.3) Consider how your shared library will be unloaded. Take a lookat the generated function ufusr_ask_unload.--------------------------------------------------------------*/#ifdef DISPLAY_FROM_USER_EXITextern void <enter a valid user exit here> (char *param, int *retcode, int rlen) {int response = 0;int error_code = 0;if ( ( UF_initialize() ) != 0 )return;if ( ( error_code = UF_STYLER_create_dialog ( "spline_dialog.dlg", CHANGE_cbs, /* Callbacks from dialog */CHANGE_CB_COUNT, /* number of callbacks*/NULL, /* This is your client data */&response ) ) != 0 ){char fail_message[133];/* Get the user function fail message based on the fail code.*/UF_get_fail_message(error_code, fail_message);UF_UI_set_status (fail_message);printf ( "%s\n", fail_message );}UF_terminate();return;}/*--------------------------------------------------------------------------This function specifies how a shared image is unloaded from memorywithin Unigraphics. This function gives you the capability to unload an internal NX Open application or user exit from Unigraphics. You can specify any one of the three constants as a return value to determinethe type of unload to perform: immediately after user function execution, via an unload selection dialog, or when Unigraphics terminates terminates. If you choose UF_UNLOAD_SEL_DIALOG, then you have the option to unload your image by selecting File->Utilities->Unload Shared Image.NOTE: A program which associates NX Open applications with the menubar MUST NOT use this option since it will UNLOAD your NX Open application image --------from the menubar.--------------------------------------------------------------------------*/extern int ufusr_ask_unload (void){/* unload immediately after application exits*/return ( UF_UNLOAD_IMMEDIATEL Y );/*via the unload selection dialog... *//*return ( UF_UNLOAD_SEL_DIALOG ); *//*when UG terminates... *//*return ( UF_UNLOAD_UG_TERMINATE ); */}/*--------------------------------------------------------------------------You have the option of coding the cleanup routine to perform any housekeeping chores that may need to be performed. If you code the cleanup routine, it is automatically called by Unigraphics.--------------------------------------------------------------------------*/extern void ufusr_cleanup (void){return;}#endif /* DISPLAY_FROM_USER_EXIT *//*-------------------------------------------------------------------------*//*---------------------- UIStyler Callback Functions ----------------------*//*-------------------------------------------------------------------------*//* -------------------------------------------------------------------------* Callback Name: CHANGE_constructor* This is a callback function associated with an action taken from a* UIStyler object.** Input: dialog_id - The dialog id indicate which dialog this callback* is associated with. The dialog id is a dynamic, * unique id and should not be stored. It is* strictly for the use in the NX Open API:* UF_STYLER_ask_value(s)* UF_STYLER_set_value* client_data - Client data is user defined data associated* with your dialog. Client data may be bound * to your dialog with UF_MB_add_styler_actions * or UF_STYLER_create_dialog.* callback_data - This structure pointer contains information* specific to the UIStyler Object type that* invoked this callback and the callback type.* -----------------------------------------------------------------------*/int SPLINE_constructor ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data){/* Make sure User Function is available. */if ( UF_initialize() != 0)return ( UF_UI_CB_CONTINUE_DIALOG );/* ---- Enter your callback code here ----- */char dir[100];const char env[255]="UGII_USER_DIR";char *basedir=NULL;tag_t part;UF_PART_load_status_t error_status;basedir=getenv(env);strcpy(dir,basedir);strcat(dir,"\\part\\spline_part.prt");if(UF_PART_open(dir,&part,&error_status)!=0){UF_free_string_array(error_status.n_parts,error_status.file_names);UF_free(error_status.statuses);return(UF_UI_CB_CONTINUE_DIALOG);}UF_free_string_array(error_status.n_parts,error_status.file_names);UF_free(error_status.statuses);double arExpValue[5];UF_MODL_eval_exp("d1",&arExpValue[0]);UF_MODL_eval_exp("d2",&arExpValue[1]);UF_MODL_eval_exp("W",&arExpValue[2]);UF_MODL_eval_exp("N",&arExpValue[3]);UF_MODL_eval_exp("L",&arExpValue[4]);UF_STYLER_item_value_type_t data_set;data_set.item_attr=UF_STYLER_V ALUE;data_set.item_id=SPLINE_SPLINE_D1;data_set.value.real=arExpV alue[0];UF_STYLER_set_value(dialog_id,&data_set);UF_STYLER_free_value(&data_set);data_set.item_attr=UF_STYLER_V ALUE;data_set.item_id=SPLINE_SPLINE_D2;data_set.value.real=arExpV alue[1];UF_STYLER_set_value(dialog_id,&data_set);UF_STYLER_free_value(&data_set);data_set.item_attr=UF_STYLER_V ALUE;data_set.item_id=SPLINE_SPLINE_W;data_set.value.real=arExpV alue[2];UF_STYLER_set_value(dialog_id,&data_set);UF_STYLER_free_value(&data_set);data_set.item_attr=UF_STYLER_V ALUE;data_set.item_id=SPLINE_SPLINE_N;data_set.value.integer=arExpValue[3];UF_STYLER_set_value(dialog_id,&data_set);UF_STYLER_free_value(&data_set);data_set.item_attr=UF_STYLER_V ALUE;data_set.item_id=SPLINE_SPLINE_L;data_set.value.real=arExpV alue[4];UF_STYLER_set_value(dialog_id,&data_set);UF_STYLER_free_value(&data_set);UF_terminate ();/* Callback acknowledged, do not terminate dialog */return (UF_UI_CB_CONTINUE_DIALOG);/* A return value of UF_UI_CB_EXIT_DIALOG will not be accepted */ /* for this callback type. You must continue dialog construction.*/}/* -------------------------------------------------------------------------* Callback Name: CHANGE_destructor* This is a callback function associated with an action taken from a* UIStyler object.** Input: dialog_id - The dialog id indicate which dialog this callback* is associated with. The dialog id is a dynamic,* unique id and should not be stored. It is* strictly for the use in the NX Open API:* UF_STYLER_ask_value(s)* UF_STYLER_set_value* client_data - Client data is user defined data associated* with your dialog. Client data may be bound * to your dialog with UF_MB_add_styler_actions * or UF_STYLER_create_dialog.* callback_data - This structure pointer contains information* specific to the UIStyler Object type that* invoked this callback and the callback type.* -----------------------------------------------------------------------*/int SPLINE_destructor ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data){/* Make sure User Function is available. */if ( UF_initialize() != 0)return ( UF_UI_CB_CONTINUE_DIALOG );/* ---- Enter your callback code here ----- */UF_terminate ();/* Callback acknowledged, do not terminate dialog. *//* A return value of UF_UI_CB_EXIT_DIALOG will not be accepted */ /* for this callback type. You must continue dialog destruction*/return (UF_UI_CB_CONTINUE_DIALOG);}/* -------------------------------------------------------------------------* Callback Name: CHANGE_ok* This is a callback function associated with an action taken from a* UIStyler object.** Input: dialog_id - The dialog id indicate which dialog this callback* is associated with. The dialog id is a dynamic, * unique id and should not be stored. It is* strictly for the use in the NX Open API:* UF_STYLER_ask_value(s)* UF_STYLER_set_value* client_data - Client data is user defined data associated* with your dialog. Client data may be bound * to your dialog with UF_MB_add_styler_actions * or UF_STYLER_create_dialog.* callback_data - This structure pointer contains information* specific to the UIStyler Object type that* invoked this callback and the callback type.* -----------------------------------------------------------------------*/int SPLINE_ok ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data){/* Make sure User Function is available. */if ( UF_initialize() != 0)return ( UF_UI_CB_CONTINUE_DIALOG );/* ---- Enter your callback code here ----- */double d1;double d2;double W;int N;double L;char exps_string[5][20];UF_STYLER_item_value_type_t data[5];data[0].item_attr=UF_STYLER_V ALUE;data[0].item_id=SPLINE_SPLINE_D1;UF_STYLER_ask_value(dialog_id,&data[0]);data[1].item_attr=UF_STYLER_V ALUE;data[1].item_id=SPLINE_SPLINE_D2;UF_STYLER_ask_value(dialog_id,&data[1]);data[2].item_attr=UF_STYLER_V ALUE;data[2].item_id=SPLINE_SPLINE_W;UF_STYLER_ask_value(dialog_id,&data[2]);data[3].item_attr=UF_STYLER_V ALUE;data[3].item_id=SPLINE_SPLINE_N;UF_STYLER_ask_value(dialog_id,&data[3]);data[4].item_attr=UF_STYLER_V ALUE;data[4].item_id=SPLINE_SPLINE_L;UF_STYLER_ask_value(dialog_id,&data[4]);d1=data[0].value.real;d2=data[1].value.real;W=data[2].value.real;N=data[3].value.integer;L=data[4].value.real;for(int i=0;i<5;i++){UF_STYLER_free_value(&data[i]);}if(d1==0||d2==0||W==0||N==0||L==0){uc1601("对话框中的数值不能为零!",1);return(UF_UI_CB_CONTINUE_DIALOG);}if(d1<=d2){uc1601("d1必须大于d2!",1);return(UF_UI_CB_CONTINUE_DIALOG);}//Modify the value of expressionsprintf(exps_string[0],"d1=%f",d1);sprintf(exps_string[1],"d2=%f",d2);sprintf(exps_string[2],"W=%f",W);sprintf(exps_string[3],"N=%d",N);sprintf(exps_string[4],"L=%f",L);//update the modlefor(int j=0;j<5;j++){UF_MODL_edit_exp(exps_string[j]);UF_MODL_update();}UF_terminate ();return ( UF_UI_CB_CONTINUE_DIALOG );}/* Callback acknowledged, terminate dialog *//* It is STRONGL Y recommended that you exit your *//* callback with UF_UI_CB_EXIT_DIALOG in a ok callback.*//* return ( UF_UI_CB_EXIT_DIALOG ); *//* -------------------------------------------------------------------------* Callback Name: CHANGE_cancel* This is a callback function associated with an action taken from a* UIStyler object.** Input: dialog_id - The dialog id indicate which dialog this callback* is associated with. The dialog id is a dynamic, * unique id and should not be stored. It is* strictly for the use in the NX Open API:* UF_STYLER_ask_value(s)* UF_STYLER_set_value* client_data - Client data is user defined data associated* with your dialog. Client data may be bound * to your dialog with UF_MB_add_styler_actions * or UF_STYLER_create_dialog.* callback_data - This structure pointer contains information* specific to the UIStyler Object type that* invoked this callback and the callback type.* -----------------------------------------------------------------------*/int SPLINE_cancel ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data){/* Make sure User Function is available. */if ( UF_initialize() != 0)return ( UF_UI_CB_CONTINUE_DIALOG );/* ---- Enter your callback code here ----- */UF_terminate ();/* Callback acknowledged, terminate dialog *//* It is STRONGL Y recommended that you exit your *//* callback with UF_UI_CB_EXIT_DIALOG in a cancel call *//* back rather than UF_UI_CB_CONTINUE_DIALOG. */return ( UF_UI_CB_EXIT_DIALOG );}/*==================================================================== =========W ARNING!! This file is overwritten by the UIStyler each time the Stylerfile is saved.Filename: spline_dialog.hThis file was generated by the NX User Interface StylerCreated by: HaoVersion: NX 4Date: 02-08-12Time: 12:29This include file is overwritten each time the UIStyler dialog issaved. Any modifications to this file will be lost.====================================================================== ========*/#ifndef SPLINE_DIALOG_H_INCLUDED#define SPLINE_DIALOG_H_INCLUDED#include <uf.h>#include <uf_defs.h>#include <uf_styler.h>#ifdef __cplusplusextern "C" {#endif/*------------------ UIStyler Dialog Definitions ------------------- *//* The following values are definitions into your UIStyler dialog. *//* These values will allow you to modify existing objects within your *//* dialog. They work directly with the NX Open API, *//* UF_STYLER_ask_value, UF_STYLER_ask_values, and UF_STYLER_set_value.*/ /*------------------------------------------------------------------- */#define SPLINE_SPLINE_D1 ("SPLINE_D1")#define SPLINE_SPLINE_D2 ("SPLINE_D2")#define SPLINE_SPLINE_W ("SPLINE_W")#define SPLINE_SPLINE_N ("SPLINE_N")#define SPLINE_SPLINE_L ("SPLINE_L")#define SPLINE_DIALOG_OBJECT_COUNT ( 5 )/*---------------- UIStyler Callback Prototypes --------------- *//* The following function prototypes define the callbacks *//* specified in your UIStyler built dialog. You are REQUIRED to*//* create the associated function for each prototype. You must *//* use the same function name and parameter list when creating *//* your callback function. *//*------------------------------------------------------------- */int SPLINE_constructor ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data);int SPLINE_destructor ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data);int SPLINE_ok ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data);int SPLINE_cancel ( int dialog_id,void * client_data,UF_STYLER_item_value_type_p_t callback_data);#ifdef __cplusplus}#endif#endif /* SPLINE_DIALOG_H_INCLUDED */。