C语言代码大全

合集下载

C语言代码大全

C语言代码大全

乘法口诀表#include <stdio.h>#include <conio.h>void main(void){int i,j,x,y;clrscr();printf("\n\n * * * 乘法口诀表* * * \n\n");x=9;y=5;for(i=1;i<=9;i++){gotoxy(x,y);printf("%2d ",i);x+=3;}x=7;y=6;for(i=1;i<=9;i++){gotoxy(x,y);printf("%2d ",i);y++;}x=9;y= 6;for(i=1;i<=9;i++){for(j=1;j<=9;j++){gotoxy(x,y);printf("%2d ",i*j);y++;}y-=9;x+=3;}printf("\n\n");}用一维数组统计学生成绩#include <stdio.h>void main(){char SelectKey,CreditMoney,DebitMoney;while(1){do{clrscr();puts("=========================");puts("| Please select key: |");puts("| 1. Quary |");puts("| 2. Credit |");puts("| 3. Debit |");puts("| 4. Return |");puts("=========================");SelectKey = getch();}while( SelectKey!='1' && SelectKey!='2' && SelectKey!='3' &&SelectKey!='4' );switch(SelectKey){case '1':clrscr();puts("================================");puts("| Your balance is $1000. |");puts("| Press any key to return... |");puts("================================");getch();break;case '2':do{clrscr();puts("==================================");puts("| Please select Credit money: |");puts("| 1. $50 |");puts("| 2. $100 |");puts("| 3. Return |");puts("==================================");CreditMoney = getch();}while( CreditMoney!='1' && CreditMoney!='2' && CreditMoney!='3' );switch(CreditMoney){case '1':clrscr();puts("=========================================");puts("| Your Credit money is $50,Thank you! |");puts("| Press any key to return... |");puts("=========================================");getch();break;case '2':clrscr();puts("==========================================");puts("| Your Credit money is $100,Thank you! |");puts("| Press any key to return... |");puts("==========================================");getch();break;case '3':break;}break;case '3':do{clrscr();puts("====================================");puts("| Please select Debit money: |");puts("| 1. $50 |");puts("| 2. $100 |");puts("| 3. $500 |");puts("| 4. $1000 |");puts("| 5. Return |");puts("====================================");DebitMoney = getch();}while( DebitMoney!='1' && DebitMoney!='2' && DebitMoney!='3' &&DebitMoney!='4' && DebitMoney!='5' );switch(DebitMoney){case '1':clrscr();puts("===========================================");puts("| Your Debit money is $50,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '2':clrscr();puts("===========================================");puts("| Your Debit money is $100,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '3':clrscr();puts("===========================================");puts("| Your Debit money is $500,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '4':clrscr();puts("===========================================");puts("| Your Debit money is $1000,Thank you! |");puts("| Press any key to return... |");puts("===========================================");getch();break;case '5':break;}break;case '4':clrscr();puts("================================");puts("| Thank you for your using! |");puts("| Good bye! |");puts("================================");return;}}模拟ATM(自动柜员机)界面#include <stdio.h> void main(){int Password=0,Number=0,price=58,i=0;while( Password != 1234 ){if( i >= 3 )return;i++;puts("Please input Password: ");scanf("%d",&Password);}i=0;while( Number!=price ){do{puts("Please input a number between 1 and 100: ");scanf("%d",&Number);printf("Your input number is %d\n",Number);}while( !(Number>=1 && Number<=100) );if( Number >= 90 ){printf("Too Bigger! Press any key to try again!\n");}else if( Number >= 70 && Number < 90 ){printf("Bigger!\n");}else if( Number >= 1 && Number <= 30 ){printf("Too Small! Press any key to try again!\n");}else if( Number > 30 && Number <= 50 ){printf("Small! Press any key to try again!\n");}else{if( Number == price ){printf("OK! You are right! Bye Bye!\n");}else if( Number < price ){printf("Sorry,Only a little smaller! Press any key to try again!\n");}else if( Number > price ){printf(" Sorry, Only a little bigger! Press any key to try again!\n");}getch();}}用二维数组实现矩阵转置/* 用二维数组实现矩阵的转置*/#include <stdio.h>#define ROW 3#define COL 4main(){int matrixA[ROW][COL],matrixB[COL][ROW];int i,j; clrscr();printf("Enter elements of the matrixA,");printf("%d*%d:\n",ROW,COL);for( i=0; i<ROW; i++ ){for( j=0; j<COL; j++ ){scanf("%d",&matrixA[i][j]);}}for( i=0; i<ROW; i++ ){for( j=0; j<COL; j++ ){matrixB[j][i] = matrixA[i][j];}}printf("MatrixB,");printf("%d*%d:\n",COL,ROW);for( i=0; i<COL; i++ ){for( j=0; j<ROW; j++ ){printf("%8d",matrixB[i][j]);}printf("\n");}printf("\n Press Any Key to Quit... \n");getch();}求解二维数组的最大/最小元素#define MAXN 20int a[MAXN][MAXN];main(){int min, /* 存储最小值*/max; /* 存储最大值*/int row,col,n;clrscr();printf("Please input the order of the matrix:\n");/* 输入方阵的阶次*/ scanf("%d",&n);printf("Please input the elements of the matrix,\n from a[0][0] to a[%d][%d]:\n",n-1,n-1);for(row=0;row<n;row++)for(col=0;col<n;col++)scanf("%d",&a[row][col]);for(min=a[0][0],row=0;row<n;row++){/* 从每行选出最大数*/for(max=a[row][0],col=1;col<n;col++)/*从row行选出最大数*/if(max<a[row][col])max=a[row][col];if(min>max)/* 保存至row行的最小数*/min=max;}printf("The minimum of maximum number is %d\n",min);for(max=a[0][0],row=0;row<n;row++)/* 每行选出最小数*/for(min=a[row][0],col=1;col<n;col++)/* 从row行选出最小数*/ if(min>a[row][col])min=a[row][col];if(max<min)/*保存至row行的最大数*/max=min;}printf("The maximum of minimum numbers is %d\n",max);printf("\nPress any key to quit...\n");getch();}利用数组求前n个质数#define N 50main(){int primes[N];int pc,m,k; clrscr();printf("\n The first %d prime numbers are:\n",N);primes[0]=2;/*2是第一个质数*/pc =1;/*已有第一个质数*/m =3;/*被测试的数从3开始*/while(pc<N){/*调整m使它为下一个质数*/k=0;while(primes[k]*primes[k]<=m)if(m%primes[k]==0){/*m是合数*/m+=2;/*让m取下一个奇数*/k=1;/*不必用primes[0]=2去测试m,所以k从一开始*/}elsek++;/*继续用下一个质数去测试*/primes[pc++]=m;m+=2;/*除2外,其余质数均是奇数*/}/*输出primes[0]至primes[pc-1]*/for(k=0;k<pc;k++)printf("%4d",primes[k]);printf("\n\n Press any key to quit...\n ");getch();}编制万年历#include "stdio.h"long int f(int year,int month){/*f(年,月)=年-1,如月<3;否则,f(年,月)=年*/if(month<3) return year-1;else return year;} long int g(int month){/*g(月)=月+13,如月<3;否则,g(月)=月+1*/if(month<3) return month+13;else return month+1;} long int n(int year,int month,int day){/*N=1461*f(年、月)/4+153*g(月)/5+日*/return 1461L*f(year,month)/4+153L*g(month)/5+day;} int w(int year,int month,int day){/*w=(N-621049)%7(0<=w<7)*/return(int)((n(year,month,day)%7-621049L%7+7)%7);} int date[12][6][7];int day_tbl[ ][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};main(){int sw,leap,i,j,k,wd,day;int year;/*年*/char title[]="SUN MON TUE WED THU FRI SAT";clrscr();printf("Please input the year whose calendar you want to know: ");/*输入年*/scanf("%d%*c",&year);/*输入年份值和掠过值后的回车*/sw=w(year,1,1);leap=year%4==0&&year%100||year%400==0;/*判闰年*/for(i=0;i<12;i++)for(j=0;j<6;j++)for(k=0;k<7;k++)date[i][j][k]=0;/*日期表置0*/for(i=0;i<12;i++)/*一年十二个月*/for(wd=0,day=1;day<=day_tbl[leap][i];day++){/*将第i+1月的日期填入日期表*/date[i][wd][sw]=day;sw=++sw%7;/*每星期七天,以0至6计数*/if(sw==0) wd++;/*日期表每七天一行,星期天开始新的一行*/} printf("\n|==================The Calendar of Year %d=====================|\n|",year);for(i=0;i<6;i++){/*先测算第i+1月和第i+7月的最大星期数*/for(wd=0,k=0;k<7;k++)/*日期表的第六行有日期,则wd!=0*/wd+=date[i][5][k]+date[i+6][5][k];wd=wd?6:5;printf("%2d %s %2d %s |\n|",i+1,title,i+7,title);for(j=0;j<wd;j++){printf(" ");/*输出四个空白符*//*左栏为第i+1月,右栏为第i+7月*/for(k=0;k<7;k++)if(date[i][j][k])printf("%4d",date[i][j][k]);else printf(" ");printf(" ");/*输出十个空白符*/for(k=0;k<7;k++)if(date[i+6][j][k])printf("%4d",date[i+6][j][k]);else printf(" ");printf(" |\n|");}/*scanf("%*c");/*键入回车输出下一个月的日历*/}puts("=================================================================|");puts("\n Press any key to quit...");getch();}对数组元素排序rest(int a[], int n){int i,low,high,t; for(i=0,low=0,high=n-1;i<=high;) {if(a[i]>0){/*a[i]与a[high]交换,随之high减1*/t=a[i];a[i]=a[high];a[high]=t;high--;}else if(a[i]==0)i++; /* 掠过该元素*/else{/*a[i]与a[low]交换,随之low增1, i增1*/t=a[i];a[i]=a[low];a[low]=t;low++;i++;}}int s[]={8,4,0,-1,6,0,-5};main(){int i;clrscr();printf("\n The arry before rest is:\n");for(i=0;i<sizeof(s)/sizeof(s[0]);i++)printf("%4d",s[i]);rest(s,sizeof(s)/sizeof(s[0]));printf("\n The arry after rest is:\n");for(i=0;i<sizeof(s)/sizeof(s[0]);i++)printf("%4d",s[i]);printf("\n Press any key to quit...\n");getch();}任意进制数的转换/* 函数trans将无符号整数n翻译成d(2<=d<=16)进制表示的字符串s */ #define M sizeof(unsigned int)*8int trans(unsigned n, int d, char s[]){static char digits[] ="0123456789ABCDEF"; /* 十六进制数字的字符*/char buf[M+1];int j, i = M;if(d<2||d>16){s[0]='\0'; /* 不合理的进制,置s为空字符串*/return 0; /* 不合理的进制,函数返回0 */}buf[i]='\0';do{buf[--i]=digits[n%d]; /*译出最低位,对应字符存入对应工作数组中*/n/=d;}while(n);/* 将译出在工作数组中的字符串复制到s */for(j=0;(s[j]=buf[i])!='\0';j++,i++);/* 其中控制条件可简写成s[j]=buf[i] */return j;}/* 主函数用于测试函数trans() */main()unsigned int num = 253;int scale[]={2,3,10,16,1};char str[33];int i;clrscr();for(i=0;i<sizeof(scale)/sizeof(scale[0]);i++){if(trans(num,scale[i],str))printf("%5d = %s(%d)\n",num,str,scale[i]);elseprintf("%5d => (%d) Error! \n",num,scale[i]);}printf("\n Press any key to quit...\n");getch();}判断回文数/* 函数circle用于判断正整数n的d进制数表示形式是否是回文数*/ int circle(int n, int d){int s=0,m=n;while(m){s=s*d+m%d;m/=d;}return s==n;}/* main函数用于测试circle函数*/int num[]={232,27,851};int scale[]={2,10,16};main(){int i,j;clrscr();for(i=0;i<sizeof(num)/sizeof(num[0]);i++)for(j=0;j<sizeof(scale)/sizeof(scale[0]);j++)if(circle(num[i],scale[j]))printf("%d -> (%d) is a Circle Number!\n",num[i],scale[j]);elseprintf("%d -> (%d) is not a Circle Number!\n",num[i],scale[j]);printf("\n Press any key to quit...\n");getch();}求解钢材切割的最佳订单#include <stdio.h>#define N 20#define DELTA 2int bestlen;int bestsele[N];int sele[N];int n;int orderlen[N];int total;main(){int i;clrscr();printf("\n Please enter total length of the steel:\n");/* 输入钢材总长*/scanf("%d",&total);printf("\n Please enter number of order:\n"); /* 输入定单数*/ scanf("%d",&n);printf("\n Please enter the orders:\n"); /* 输入各定单*/for(i=0;i<n;i++)scanf("%d",&orderlen[i]);bestlen=0; /*最佳解用料的初值*/for(i=0;i<n;i++)sele[i]=bestsele[i]=0; /*置当前选择和最佳选择初值*/try(); /* 调用函数求解*/for(i=0;i<n;i++) /* 输出结果*/if(bestsele[i])printf("order %d length = %d\n",i+1,orderlen[i]);printf("\n Press any key to quit...");getch();}try(){int i,len;for(len=i=0;i<n;i++) /* 求当前选中的用料量*/if(sele[i])len+=orderlen[i]+DELTA;if(len-DELTA<=total) /* 注意最后一段可能不需要切割*/{if(bestlen < len){/* 找到一个更好的解*/bestlen = len;for(i=0;i<n;i++)bestsele[i]=sele[i];}for(i=0;i<n;i++) /* 对所有未选定单逐一作选中尝试循环*/if(!sele[i]){sele[i]=1; /* 做选中尝试*/try();sele[i]=0;}}}指向数组的指针main(){int x,y,z; /* 定义三个int型变量*/int *xp = &x, /* 定义指针变量xp,并赋值为x的地址,使xp指向x */ *yp = &y, /* 定义指针变量yp,并赋值为y的地址,使yp指向y */*zp = &z; /* 定义指针变量zp,并赋值为z的地址,使zp指向z */int t;clrscr();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");/*运行程序需带整数参数*/ exit(0);}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语言程序设计 入门源代码代码集合【精选文档】

#include 〈stdio.h〉void print_star(void){printf("*****************\n"); }void print_welcome(void){printf(”C language,welcome!\n");}void main(){print_star();print_welcome();print_star();getchar();}演示2#include "stdio。

h"int sum(int i,int j){return(i + j);}void main(){int n1,n2;printf("input 2 numbers:\n”);scanf("%d%d”,&n1,&n2);printf("the sum = %d\n",sum(n1,n2));getchar();}演示3#include "stdio。

h"int maxnum(int,int,int);main(){int a,b,c;printf("Please enter 3 numbers:\n");scanf(”%d,%d,%d”,&a,&b,&c);printf(”Maxnum is %d\n",maxnum(a,b,c));}int maxnum(int x,int y,int z){int max=x;if(y>max)max = y;if(z>max)max = z;return max;}演示4#include 〈stdio。

h〉int s1(int n){int j,s;s=0;for(j=1;j<=n;j++)s=s+j;return s;}int sum(int n){int i,s=0;for(i=1;i<=n;i++)s=s+s1(i);return s;}void main(){int n;printf(”n:”);scanf(”%d",&n);printf("s=%d\n”,sum(n));}演示5#include <stdio.h〉void func(int n){int i;for(i=n-1;i〉=1;i--)n=n+i;printf("n=%d\n",n);}void main(){int n;printf("Input n:");scanf("%d”,&n);func(n);printf(”n=%d\n",n);}演示6#include <stdio。

好玩的c语言代码

好玩的c语言代码

好玩的c语言代码以下是一些好玩的 C 语言代码:1. Hello World#include <stdio.h>int main() {printf("Hello World!\n");return 0;}2. 乘法表#include <stdio.h>int main() {int i, j;for(i = 1; i <= 9; i++) {for(j = 1; j <= i; j++) {printf("%d x %d = %d ",j,i,i*j);}printf("\n");}return 0;}3. 猜数字游戏#include <stdio.h>#include <stdlib.h>#include <time.h>int main() {int number, guess, count = 0;srand(time(NULL));number = rand() % 100 + 1; // 随机一个 1~100 的数printf("猜一个 1~100 的数字:\n");do {scanf("%d",&guess);count++;if(guess > number) {printf("太大了,请继续猜:\n");} else if(guess < number) {printf("太小了,请继续猜:\n");} else {printf("恭喜你,猜对了!你一共猜了 %d 次。

\n",count); }} while(guess != number);return 0;}4. 计算圆的周长和面积#include <stdio.h>#define PI 3.1415926535int main() {float r, circumference, area;printf("请输入圆的半径:\n");scanf("%f",&r);circumference = 2 * PI * r; // 周长公式area = PI * r * r; // 面积公式printf("圆的周长:%f\n",circumference);printf("圆的面积:%f\n",area);return 0;}5. 温度转换#include <stdio.h>int main() {float fahrenheit, celsius;printf("请输入华氏度:\n");scanf("%f",&fahrenheit);celsius = (fahrenheit - 32) * 5 / 9; // 华氏度转摄氏度公式 printf("摄氏度:%.2f\n",celsius);return 0;}。

C语言入门基础代码(20条案例)

C语言入门基础代码(20条案例)

C语言入门基础代码(20条案例)下面是20条基础案例:1. 输出Hello, World!#include <stdio.h> // 使用标准输入输出库int main() {printf("Hello, World!\n"); // 输出字符串return 0; // 返回程序执行成功}2. 判断一个数是否为偶数#include <stdio.h> // 使用标准输入输出库int main() {int num; // 定义变量printf("请输入一个整数:");scanf("%d", &num); // 从控制台输入一个整数if(num % 2 == 0) { // 如果余数为0说明是偶数printf("%d 是偶数\n", num);} else {printf("%d 是奇数\n", num);}return 0;}3. 计算两个数的和#include <stdio.h> // 使用标准输入输出库int main() {int a, b; // 定义变量int sum; // 定义变量printf("请输入两个整数:");scanf("%d%d", &a, &b); // 从控制台输入两个整数sum = a + b; // 求和printf("%d + %d = %d\n", a, b, sum); // 输出结果return 0;}4. 求一个数的平方#include <stdio.h> // 使用标准输入输出库int main() {int num; // 定义变量int square; // 定义变量printf("请输入一个整数:");scanf("%d", &num); // 从控制台输入一个整数square = num * num; // 求平方printf("%d 的平方是%d\n", num, square); // 输出结果return 0;}5. 判断一个字符是否为数字#include <stdio.h> // 使用标准输入输出库#include <ctype.h> // 使用字符函数库int main() {char ch; // 定义变量printf("请输入一个字符:");scanf("%c", &ch); // 从控制台输入一个字符if(isdigit(ch)) { // 判断是否为数字printf("%c 是数字\n", ch);} else {printf("%c 不是数字\n", ch);}return 0;}6. 计算数组元素的平均值#include <stdio.h> // 使用标准输入输出库int main() {int arr[] = {1, 2, 3, 4, 5}; // 定义数组int len = sizeof(arr) / sizeof(int); // 数组长度int sum = 0; // 定义变量int avg; // 定义变量for(int i = 0; i < len; i++) { // 遍历数组sum += arr[i]; // 累加求和}avg = sum / len; // 求平均值printf("数组的平均值是%d\n", avg); // 输出结果return 0;}7. 按照下标访问数组元素#include <stdio.h> // 使用标准输入输出库int main() {int arr[] = {1, 2, 3, 4, 5}; // 定义数组int len = sizeof(arr) / sizeof(int); // 数组长度for(int i = 0; i < len; i++) { // 遍历数组printf("arr[%d] = %d\n", i, arr[i]); // 输出每个元素}return 0;}8. 使用指针访问数组元素#include <stdio.h> // 使用标准输入输出库int main() {int arr[] = {1, 2, 3, 4, 5}; // 定义数组int len = sizeof(arr) / sizeof(int); // 数组长度int *p = arr; // 把数组首地址赋给指针变量for(int i = 0; i < len; i++) { // 遍历数组printf("arr[%d] = %d\n", i, *(p + i)); // 输出每个元素}return 0;}9. 求Fibonacci 数列的第n 项#include <stdio.h> // 使用标准输入输出库int main() {int n; // 定义变量int a = 0, b = 1, c; // 定义变量printf("请输入一个正整数:");scanf("%d", &n); // 从控制台输入一个整数for(int i = 1; i <= n; i++) { // 求Fibonacci 数列的第n 项c = a + b;a = b;b = c;}printf("Fibonacci 数列的第%d 项是%d\n", n, a); // 输出结果return 0;}10. 使用递归计算阶乘#include <stdio.h> // 使用标准输入输出库int factorial(int n) { // 定义递归函数if(n == 0 || n == 1) {return 1;} else {return n * factorial(n - 1);}}int main() {int n; // 定义变量printf("请输入一个非负整数:");scanf("%d", &n); // 从控制台输入一个整数int result = factorial(n); // 调用递归函数计算阶乘printf("%d 的阶乘是%d\n", n, result); // 输出结果return 0;}11. 判断一个数是否是质数#include <stdio.h>#include <stdbool.h>bool isPrime(int num) {if(num <= 1) {return false; // 小于等于1的数都不是质数}for(int i = 2; i * i <= num; i++) { // 只要从2到根号num遍历就可以了if(num % i == 0) {return false; // 如果存在因子,则不是质数}}return true;}int main() {int num;printf("请输入一个整数:");scanf("%d", &num);bool result = isPrime(num); // 调用isPrime函数if(result) {printf("%d 是质数\n", num);} else {printf("%d 不是质数\n", num);}return 0;}12. 计算圆的面积和周长#include <stdio.h>const double PI = 3.1415926;int main() {double r, area, perimeter;printf("请输入圆的半径:");scanf("%lf", &r);area = PI * r * r; // 计算面积perimeter = 2 * PI * r; // 计算周长printf("圆的面积是%.2f,周长是%.2f\n", area, perimeter);return 0;}13. 计算斐波那契数列的前n 项#include <stdio.h>int main() {int n;printf("请输入要输出的斐波那契数列项数:");scanf("%d", &n);int a = 0, b = 1, c; // 定义三个变量for(int i = 1; i <= n; i++) { // 输出前n项斐波那契数列printf("%d ", a);c = a + b;a = b;b = c;}printf("\n"); // 换行return 0;}14. 嵌套循环输出九九乘法表#include <stdio.h>int main() {for(int i = 1; i <= 9; i++) { // 控制行数for(int j = 1; j <= i; j++) { // 控制列数printf("%d*%d=%-2d ", j, i, i * j); // 左对齐输出}printf("\n"); // 换行}return 0;}15. 获得数组的最大值和最小值#include <stdio.h>int main() {int arr[] = {3, 5, 8, 1, 4, 9, 6, 2, 7};int len = sizeof(arr) / sizeof(int);int max = arr[0], min = arr[0]; // 假设第一个元素既是最大值也是最小值for(int i = 1; i < len; i++) {if(arr[i] > max) { // 更新最大值max = arr[i];}if(arr[i] < min) { // 更新最小值min = arr[i];}}printf("数组的最大值是%d,最小值是%d\n", max, min);return 0;}16. 判断一个数是否为回文数```c#include <stdio.h>#include <stdbool.h>bool isPalindrome(int num) {if(num < 0) { // 负数不是回文数return false;}int temp = num, reversed = 0; // 定义需要用到的变量while(temp != 0) { // 反转整数reversed = reversed * 10 + temp % 10;temp /= 10;}return (num == reversed); // 如果反转后等于原来的数,则为回文数}int main() {int num;printf("请输入一个整数:");scanf("%d", &num);bool result = isPalindrome(num);if(result) {printf("%d 是回文数\n", num);} else {printf("%d 不是回文数\n", num);}return 0;}17. 将字符串反转输出#include <stdio.h>#include <string.h>int main() {char str[100];printf("请输入一个字符串:");scanf("%s", str);int len = strlen(str);for(int i = len - 1; i >= 0; i--) { // 倒序输出printf("%c", str[i]);}printf("\n"); // 换行return 0;}18. 将一个二维数组按列排序#include <stdio.h>void sortCols(int arr[][3], int rows) {for(int j = 0; j < 3; j++) { // 按列排序for(int i = 0; i < rows - 1; i++) {for(int k = i + 1; k < rows; k++) {if(arr[i][j] > arr[k][j]) { // 比较大小并交换int temp = arr[i][j];arr[i][j] = arr[k][j];arr[k][j] = temp;}}}}}int main() {int arr[][3] = {{2, 5, 9}, {7, 6, 1}, {4, 3, 8}};int rows = sizeof(arr) / sizeof(arr[0]); // 计算数组的行数sortCols(arr, rows); // 调用函数排序for(int i = 0; i < rows; i++) { // 输出排序后的数组for(int j = 0; j < 3; j++) {printf("%d ", arr[i][j]);}printf("\n"); // 换行}return 0;}19. 判断一个字符串是否为回文串#include <stdio.h>#include <string.h>#include <stdbool.h>bool isPalindrome(char str[]) {int len = strlen(str);for(int i = 0; i < len / 2; i++) { // 判断左右字符是否一样if(str[i] != str[len - i - 1]) {return false;}}return true;}int main() {char str[100];printf("请输入一个字符串:");scanf("%s", str);bool result = isPalindrome(str); // 调用函数判断是否为回文串if(result) {printf("%s 是回文串\n", str);} else {printf("%s 不是回文串\n", str);}return 0;}20. 将一个整数转换成二进制数并输出#include <stdio.h>void decToBin(int num) {if(num > 1) { // 递归调用decToBin(num / 2);}printf("%d", num % 2); // 每次输出余数}int main() {int num;printf("请输入一个十进制数:");scanf("%d", &num);printf("%d 的二进制数为", num);decToBin(num); // 调用函数输出二进制数printf("\n"); // 换行return 0;}。

初学C语言常用简单程序代码

初学C语言常用简单程序代码

初学C语言常用简单程序代码C语言是一种广泛应用于软件开发和系统编程的高级编程语言。

对于初学者来说,掌握一些常用的简单程序代码是非常重要的,因为它们可以帮助你建立起对C 语言基础知识的理解,并为以后的学习打下坚实的基础。

在本文中,我将为你提供一些常见的C语言简单程序代码示例,帮助你更好地入门。

1. Hello World```c#include <stdio.h>int main() {printf("Hello, World!");return 0;}```这是C语言中最简单的程序,它会在屏幕上输出"Hello, World!"。

通过这个简单的示例,你可以学会如何使用printf函数来输出文本。

2. 计算两个数的和```c#include <stdio.h>int main() {int num1, num2, sum;printf("请输入两个整数:");scanf("%d %d", &num1, &num2);sum = num1 + num2;printf("两个数的和是:%d", sum);return 0;}```这个程序示例演示了如何从用户输入中读取两个整数,并计算它们的和。

通过使用scanf函数,我们可以读取用户输入的值,并使用printf函数将结果输出到屏幕上。

3. 判断一个数是奇数还是偶数```c#include <stdio.h>int main() {int num;printf("请输入一个整数:");scanf("%d", &num);if(num % 2 == 0) {printf("%d是偶数", num);} else {printf("%d是奇数", num);}}```这个程序示例展示了如何判断一个数是奇数还是偶数。

c语言初学必背代码

c语言初学必背代码

11l.成绩判断#in elude <stdio.h> int mai n(){//成绩int score;printf("请输入你的成绩:\n");sca nf("%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的和#in clude <stdio.h>int mai n(){int sum = 0; //存结果变量int i;for(i=1;i <= 100;i++){sum = sum + i;}prin tf("sum=%d\n", sum); }113.最大公约数#i nclude <stdio.h>//求m,n的最大公约数int mai n(){int m, n;int i, k;printf("请输入两个数:");sca nf("%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.最小公倍数#in elude <stdio.h>//求m,n的最小公倍数int mai n(){int m, n;int max, min; 〃m,n 中较大,较小的那个int k; //max, 2*max, 3*max,printf("请输入两个数:");scan f("%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.金字塔#i nclude <stdio.h>//金字塔int mai n(){int i; // 外层int j; // 内层for(i=1;i<=10;i++){//当前是在第i行//先补空格10-i个for(j=1;jv=10-i;j++)}//再打2i-1个*for(j=1;j<=2*i-1;j++){prin tf("*");}prin tf("\n");}}printf(""); 〃6.九九乘法表#in clude <stdio.h>//打印九九乘法表int mai n(){int i,j;for(i=1;i<=9;i++) // 外层一定是9行{for(j=1; jv=i; j++) // 内层第几行走几遍{printf("%d*%d=%d ", i, j, i*j);}prin tf("\n");}}〃7.百钱买百鸡#i nclude <stdio.h>/**百钱买百鸡,类似1,2,5凑100银币问题int mai n2(){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 mai n3()int cou nt = 0; // 情况数for(i=0; i<=20; i++) 〃5 分个数{for(j=0; j<=50; j++) 〃2 分个数{if( ( 5*i + 2*j ) <= 100 ){coun t++;printf("%d: 5 分%d 个,2 分%d 个,1 分%d 个\n", count, i, j, 100-5*i-2*j);}}}}〃8. —维数组的最大值、最小值、平均值#i nclude <stdio.h>#defi ne N 10 //宏定义常量int mai n()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];}prin tf("max=%d, min=%d\n", max min);prin tf("average = %.2lf\n", sum/N); }〃9.二维数组的最大值、最小值、平均值#i nclude <stdio.h>int mai n(){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列{prin tf("%5d ", a[i][j]);if(a[i][j] < min)min = a[i][j];}prin tf("\n");}average = sum / (3*4);prin tf("max=%d, mi n=%d, avg=%.2lf\n", max, min, average);}〃10.二维数组转置#in elude <stdio.h>//二维数组转置:行变列,列变行int mai n()sum += a[i][j];{int i; //第几行if(a[i][j] > max)max = a[i][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]);}prin tf("\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++){prin tf("%5d", b[i][j]);}prin tf("\n");}}//11.冒泡排序#in elude <stdio.h>#defi ne N 10 //宏定义常量int mai n(){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;}}} 〃12.结构冒泡排序#in elude <stdio.h>//结构定义,用户自定义类型typedef struct stude nt{char sno [20]; // 学号char name[20]; // 姓名int age; // 年龄char gen der; // 性^char tel[20]; // 电话};int mai n(){int i;int j;double sum = 0;for(i=0; i<N; i++){prin tf("%d ",a[i]);;}prin tf("\n");}struct student tmp; //两两交换临时用;//结构数组struct stude nt team[5];for(i=0; i<5; i++){printf("请输入第%d个队员的信息:\n", i+1);sca nf("%s %s %d %c %s",team[i].s no, 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;}}}//取值prin tf("%-12s %-10s %-5s %-5s %-15s \n","学号","姓名","年龄","性别","电话");for(i=0; i<5; i++){prin tf("%-12s %-10s %-5d %-5c %-15s \n", team[i].sno, team[i].name, team[i].age, team[i].gender, team[i].tel);}}〃13.结构数组找年龄最大值#i nclude <stdio.h>//结构定义,用户自定义类型typedef struct stude nt{char sno [20]; // 学号char name[20]; // 姓名int age; // 年龄char gen der; // 性^char tel[20]; // 电话};int main(){int i;struct stude nt tmp; //找最大临时用//结构数组struct stude nt team[5];for(i=0; i<5; i++){printf("请输入第%d个队员的信息:\n", i+1);sca nf("%s %s %d %c %s" team[i].s no, team[i]. name, &team[i].age, &team[i].gender, team[i].tel);}//取值prin tf("%-12s %-10s %-5s %-5s %- 15s\n","学号","姓名","年龄","性别"," 电话");for(i=0; i<5; i++){prin tf("%-12s %-10s %-5d %-5c % -15s\n", team[i].s no, team[i]. name,team[i].age, team[i].gender, team[i].tel);}//找学号最大的那一个tmp = team[0];for(i=1; i<5; i++){ char name[20]; // 姓名if(strcmp(team[i].s no,tmp.s no) > int age; // 年龄0 ) char gen der; // 性^{ char tel[20]; // 电话tmp = team[i]; };}} //文件读写printf("学号最大的队员如下:\n"); int mai n()prin tf("%-12s %-10s %-5d %-5c % {-15s\n", tmp.s no, tmp. name, tmp.age, struct stude nt * s, * p1; //个数未知tmp.gender, tmp.tel); FILE * fp;} int i, n = 0;char buf[1024];//fgets 缓冲区〃14.文件读写//打开文件fp = fope n("e:\\test.txt", "r");#i nclude <stdio.h>#i nclude <stdlib.h>//结构定义,用户自定义类型typedef struct stude nt{char sno [20]; // 学号while(fgets(buf, 1024, fp) != NULL)n++;fclose(fp);//指向一个可以存储n个student结构的内存空间stude nt(struct*)malloc(sizeof(struct student) * n);free(s);pl = s; //不要动头位置s的值}//打开文件fp = fope n( "e:\\test.txt", "r");for(i=0; i<n; i++){//从文件中读入一行fscanf(fp, "%s %s %d %c %s", p1->s no, p1- >n ame, &p1->age, &p1->ge nder, p1->tel);p1++;}fclose(fp);p1 = s;for(i=0; i<3; i++){prin tf("%s %s %d %c %s\n",p1->s no, p1- >n ame, p1->age, p1->ge nder, p1->tel);〃15.输入三角形三边长计算周长和面积#in clude<stdio.h>#in clude<math.h>int mai n(){double area,perimeter,s,a,b,c;printf("请输入三边长a b c:");sca nf("%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;prin tf("area=%.2f,perimeter=%.2f\n ",area,perimeter);else{printf("三边长无法构成三角形\n");}return 0;}〃16.输入年份和月份输出对应那一月的天数要处理闰年#i ncludeint main(){int year,m on th;int leap =0;sca nf("%d %d", &year,&mon th);if((year %4==0 && year %100 !=0)|| year %400 ==0) // 闰年2 月29 天{switch(mo nth){case 1:case 3:case 5:case 7:case 8:case 10:case 12:pri ntf("31");break;case 4:case 6:case 9:case 11:pri ntf("30");break;case2:pri ntf("%d",28+leap);break;default:pri ntf("error");break } return 0;}leap=1; }//18.100到200所有的素数#i nclude <stdio.h>1117.1 , 2 , 5分硬币问题 #i nclude <stdio.h> int main(){int sum = 0;for(int i=0; i<=20; i++) 〃5 分{for(int j=0; j<=50; j++) 112分 {if(5*i + 2*j <= 100) sum++; elsebreak;} }printf("%d\n", sum); }int main() {int i,j,n;//外层for(i=100; i<=200; i++){n = i;//内层for(j=2;j<=n-1;j++) {if(n%j == 0)break; //不是素数} if(j==n)// 没找到printf("%d 是素数 \n", n); elseprintf("%d 不是素数 \n", n);}}〃19.输入一个数n , 计算 12+22+32+ …+n 2void swap(i nt *pa, int *pb){int tmp =*pa; *pa = *pb; *pb = tmp;int i, k;sca nf("%d", &k); i = 1;while(i <= k) {sum = sum + i * i; i++; }prin tf("sum = %d\n", sum); }prin tf("a=%d, b=%d\n", a, b);}II 定义一个方法swap()通过指针交换两个整#i nclude <stdio.h> int main() {int sum = 0;int mai n(){int a = 3; int b = 5;int *pa = &a;int *pb = &b; swap(pa, pb);〃20.指针交换数,并在main()中调用#i nclude <stdio.h>。

100行C语言代码

100行C语言代码

#include <stdio.h>#include <time.h>#include <windows.h>#include <stdlib.h>int renji();int renren();int renji(){int n,k,a,b,m;printf("分别输入山数,每次最大搬山量,用空格隔开,回车结束\n");scanf("%d%d",&n,&k);printf("开始了,你先来吧。

\n");for(;n>0;){scanf("%d",&a);if(a>k){printf("搬山数需小于%d个\n",k);continue;}if(n-a<0){printf("没有那么多山了。

\n");continue;}if(a==0){printf("不能不搬山\n");continue;}if(n-a==1){printf("好吧你赢了\n");break;}if(n-a==0){printf("哈哈哈哈,你输了,猪\n");break;}n=n-a;if(n>k){b=(n-1)%(k+1);if(b==0)b=1;}else b=n-1;n=n-b;printf("对手搬%d个,剩%d个\n",b,n);}return 0;}int renren(){int a,b,c,d,i,j;printf("分别输入人数、山数,每次最大搬山量,用空格隔开,回车结束\n");scanf("%d%d%d",&a,&b,&c);if(a<2){printf("%d个人怎么玩。

C语言代码大全

C语言代码大全

C语言代码大全C语言是一种高级程序设计语言,广泛应用于计算机科学和软件开发领域。

它以其简洁、高效的特点而备受青睐。

本文将为您介绍一些常用的C语言代码,包括输入输出、流程控制、函数调用、数据结构等方面的代码示例。

一、输入输出1. 标准输入输出```c#include <stdio.h>int main() {int num;printf("请输入一个整数:");scanf("%d", &num);printf("您输入的数字是:%d\n", num);return 0;}```2. 文件读写```cint main() {FILE *file;char str[100];// 写入文件file = fopen("data.txt", "w");fprintf(file, "Hello, World!");fclose(file);// 读取文件file = fopen("data.txt", "r");fscanf(file, "%s", str);printf("从文件中读取的内容是:%s\n", str); fclose(file);return 0;}```二、流程控制1. 条件语句```cint main() {int num = 10;if (num > 0) {printf("该数字是正数。

\n"); } else if (num < 0) {printf("该数字是负数。

\n"); } else {printf("该数字是零。

\n"); }return 0;}```2. 循环语句```c#include <stdio.h>int main() {int num = 5;// while循环while (num > 0) {printf("当前数字:%d\n", num); num--;}// for循环for (int i = 0; i < 5; i++) {printf("当前数字:%d\n", i);}// do-while循环do {printf("当前数字:%d\n", num); num++;} while (num < 5);return 0;}```三、函数调用```c#include <stdio.h>int add(int a, int b) {return a + b;}int main() {int num1 = 5;int num2 = 3;int result = add(num1, num2);printf("两个数的和为:%d\n", result); return 0;}```四、数据结构1. 数组```c#include <stdio.h>int main() {int arr[5] = {1, 2, 3, 4, 5};for (int i = 0; i < 5; i++) {printf("数组元素:%d\n", arr[i]); }return 0;}```2. 结构体```c#include <stdio.h>struct Student {char name[20];int age;};int main() {struct Student stu1;strcpy(, "Tom");stu1.age = 18;printf("学生姓名:%s\n", ); printf("学生年龄:%d\n", stu1.age); return 0;}```以上只是C语言代码中的一小部分示例,C语言是一门非常庞大的编程语言,拥有众多的功能和特性。

C语言基础训练代码(10条)

C语言基础训练代码(10条)

C语言基础训练代码(10条)1. 输入两个整数,输出它们的和。

#include <stdio.h>int main() {int a, b, sum;scanf("%d%d", &a, &b);sum = a + b;printf("%d + %d = %d\n", a, b, sum);return 0;}2. 计算一个整数的阶乘。

#include <stdio.h>int main() {int n, i;long long fact = 1;scanf("%d", &n);for (i = 1; i <= n; ++i) {fact *= i;}printf("%d! = %lld\n", n, fact);return 0;}3. 输入三角形三边的长度,判断是否为直角三角形。

#include <stdio.h>int main() {double a, b, c;scanf("%lf%lf%lf", &a, &b, &c);if ((a*a + b*b == c*c) || (a*a + c*c == b*b) || (b*b + c*c == a*a))printf("是直角三角形\n");elseprintf("不是直角三角形\n");return 0;}4. 输入一个字符,判断它是否为大写字母。

#include <stdio.h>int main() {char ch;scanf("%c", &ch);if (ch >= 'A' && ch <= 'Z')printf("%c是大写字母\n", ch);elseprintf("%c不是大写字母\n", ch);return 0;}5. 输入一个整数,判断它是否为素数。

C语言代码大全(可编辑修改word版)

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语言源代码

经典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.hvoid main() {int i, flag, year, month, day, dayth;int month_day[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; 牰湩晴尨请输入年/ 月/日:\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];printf(%d/%d/%d是第%d天\n, year, month, day, dayth);}2、30个数中找最小的数及其位置#include stdio.h# define SIZE 30void main() {int i;float data[SIZE];int min;牰湩晴尨请输入%d个浮点数:\n,SIZE);for (i = 0; i < SIZE; i++) {//scanf_s(%f, &data[i]);data[i] = rand() % 30 + 1;, data[i]);、printf(%f}min = 0;for (i = 1; i < SIZE; i++) {if (data[i] < data[min])min = i;}牰湩晴尨最小值是%5.2f,位置是]\n, data[min], min); }3、30个数从小到大排序(1)#include stdio.h# define SIZE 30void main() {int i,j;float data[SIZE],temp;int min;牰湩晴尨请输入%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])min = j;temp = data[min];data[min] = data[i];data[i] = temp;}printf(\排序后的结果是:\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);牰湩晴尨排序前:);show_array(score, SIZE);sort(score, SIZE);牰湩晴尨排序后:);show_array(score, SIZE);}void accept_array(float a[], int size) { int i;牰湩晴尨请输入%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++)%5.2f, a[i]); printf(printf(\);}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 10void main() {int a[SIZE] = { 1,2,3,4,5,6,7,8,9,10 };int *pa, i;pa = &a[0];//pa=a;printf(\);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];牰湩晴尨请输入%d整型数:,SIZE); for (; pa < qa + SIZE; pa++)scanf_s(%d, pa);for (pa--; qa <= pa; pa--)%d, *pa);printf(}5、两字符串相连:#include stdio.h #include string.hvoid str_cat(char str1[], char str2[]); void main() {int i, j;char str1[160];char str2[80];牰湩晴尨请输入第一个字符串:); gets(str1);牰湩晴尨请输入第二个字符串:);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';}转置)a,b、二维数组(6#include stdio.h void main() {int i, j, b[2][3];6} };for (i = 0; i < 2; i++) {for (j = 0; j < 3; j++)b[i][j] = a[j][i];}printf(\a:\n);for (i = 0; i < 3; i++) {for (j = 0; j < 2; j++)printf(], a[i][j]);printf(\);}printf(\b:\n);for(i = 0; i < 2; i++) {for (j = 0; j < 3; j++)printf(], b[i][j]);printf(\);}}7、输入一个二维数组并输出(指针)#include stdio.hvoid 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 10void maopao(int a[]);void main() {int a[10];int i;牰湩晴尨请输入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轮排序9-ifor (j = 0; j < 9 - i; j++)//每轮进行次交换{if (a[j] > a[j + 1]){temp = a[j];a[j] = a[j + 1];//大的沉底,小的上浮a[j + 1] = temp;}}}牰湩晴尨排序结果:\n);for (i = 0; i < 10; i++)printf(M, 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中各元素,且两数组仍保持非降序排列。

初学编程100个代码大全c语言

初学编程100个代码大全c语言

初学编程100个代码大全c语言当初学编程时,了解一些常见的代码示例是非常有帮助的。

以下是一些常见的C语言代码示例,总共100个,供你参考:1. Hello World程序:c.#include <stdio.h>。

int main() {。

printf("Hello, World!\n");return 0;}。

2. 计算两个数的和:#include <stdio.h>。

int main() {。

int num1, num2, sum;printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); sum = num1 + num2;printf("Sum = %d\n", sum);return 0;}。

3. 判断一个数是奇数还是偶数:#include <stdio.h>。

int main() {。

int num;printf("Enter a number: ");scanf("%d", &num);if (num % 2 == 0) {。

printf("%d is even.\n", num); } else {。

printf("%d is odd.\n", num); }。

return 0;}。

4. 判断一个数是正数、负数还是零:c.#include <stdio.h>。

int main() {。

int num;printf("Enter a number: ");scanf("%d", &num);if (num > 0) {。

printf("%d is positive.\n", num);} else if (num < 0) {。

经典C语言源代码

经典C语言源代码

经典C语言源代码1、(1)某年某月某日是星期几#include<>int main(){int year, month, day;while (scanf_s("%d%d%d", &year, &month, &day) != EOF){if (month == 1 || month == 2)d.%d", &start[0], &start[1], &start[2]);printf("请输入结束日期,如:\n");scanf_s("%d.%d.%d", &end[0], &end[1], &end[2]);int sum = 0;for (int mid = start[0]; mid < end[0]; mid++) {if ((mid % 400 == 0) || (mid % 4 == 0 && mid % 100 != 0)) { sum = sum + 366;}elsesum = sum + 365;}sum = sum - indexday(start[0],start[1],start[2]) +indexday(end[0],end[1],end[2]);printf("在%d.%d.%d-%d.%d.%d之间有%d天\n",start[0],start[1],start[2],end[0],end[1],end[2], sum);}int indexday(int year, int month, int day) {int i, flag, dayth;int month_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];return dayth;}18、递归求1*1+2*2+3*3+n*n#include ""long Element(int n) {if (n == 1)return 1 * 1;elsereturn Element(n - 1) + n*n; }void main() {int n;printf("请输入n的值:\n");scanf_s("%d", &n);printf("所求值为%d\n", Element(n));}19、最大公约数(辗转相除)#include<>void main() /* 辗转相除法求最大公约数*/{int m, n, a, b, t, c;printf("Input two integer numbers:\n");scanf_s("%d%d", &a, &b);m = a; n = b;while (b != 0) /* 余数不为0,继续相除,直到余数为0 */ {c = a%b; a = b; b = c;}printf("The largest common divisor:%d\n", a);printf("The least common multiple:%d\n", m*n / a); }20、杨辉三角#include<>void main(){int i, j, n, k;printf("Enter n:"); scanf_s("%d", &n);for (i = 1; i <= n; i++){k = 1;for (j = 1; j<i; j++){printf("%3d", k);k = k*(i - j) / j;}//每次要打印的下一个数等于前一个数乘以其所在行数和列数的差再除以其列数printf("%3d", k);printf("\n");}}21、约瑟夫#include <>void main(){int n, m, i, s=0;printf ("Enter n: m: ");scanf("%d%d", &n, &m);for (i=2; i<=n; i++) s=(s+m)%i;printf ("The winner is %d\n", s+1); }22、斐波拉契#include<>void main(){long f, f1, f2; int i, n;printf("Enter n : ");scanf_s("%d", &n);f1 = 1;f2 = 1;printf("%10d%10d", f1, f2);for (i = 1; i <= n; i++){f = f1 + f2;printf("%10d", f);f1 = f2; f2 = f;if (i % 10 == 0)printf("\n");}}23、海滩上有一堆桃子,五只猴子来分。

c语言代码

c语言代码
1003
#include<stdio.h>
int main()
{
int m,n,a,b,t;
while(scanf("%d %d",&n,&m),m!=0,n!=0)
{
a=(4*n-m)/2;
b=(m-2*n)/2;
t=2*a+4*b;
if(t!=m||a<0||b<0)
{
for(j=1;j<=i;j++)
printf(" ");
for(l=h-2*i;l>0;l--)
printf("*");
printf("\n");
}
}
return 0;
}
1070 least common multiple
x=2*(x+1);
printf("%d\n",x);
}
return 0;
}
1063 养兔子
#include<stdio.h>
int main()
{
__int64 a[100];
int m,n,i,j,k;
while(scanf("%d",&n),n!=0)
}
}
printf("\n");
}
return 0;
}
1062
#include<stdio.h>
int main()
{
int n,i,j,x;

C语言经典算法C语言代码大全

C语言经典算法C语言代码大全

C语言经典算法C语言代码大全一、排序算法1、冒泡排序它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。

设数组为a[0…n-1]C语言实现如下://冒泡排序void bubbleSort(int arr[], int n)int i, j, temp;bool flag;//表示n次排序过程for(i = 0; i < n - 1; i++)//每次排序将最大的数放到最右边flag = false;for(j= 0; j< n-1-i; j++)if(arr[j] > arr[j+1])temp = arr[j];arr[j] = arr[j+1];arr[j+1] = temp;flag = true;}}//如果趟排序没有进行数据交换,说明数据已经有序if (flag == false)break;}}2、快速排序它采用了分治法的思想,基于快速排序的思想,可以对数组进行非常快速的排序。

设数组为a[0…n-1]C语言实现如下://快速排序// arr[left] 为起始值,arr[right] 为末尾值void quickSort(int arr[], int left, int right)int i, j, base;if (left > right)return;}i = left;j = right;base = arr[left];//定义基准值,可以是数组的第一个值while (i != j)// 因为基准值是 arr[left],所以左边右移,直到找到小于基准值的值while (arr[j] >= base && i < j)j--;}// 因为基准值是 arr[left],所以右边左移while (arr[i] <= base && i < j)i++;}//如果i<j,表示找到了,交换位置if (i < j)int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}}//将基准值放到i位置arr[left] = arr[i];。

3.C语言代码汇总

3.C语言代码汇总

1-1.输出指定字符串,SayHello#include <stdio.h>void main(){printf("---------------------------\n");printf(" This my first C program.\n");printf(" Hello ,C program.\n");printf("---------------------------\n");void reaction();reaction();}void reaction(){printf("******************************\n"); printf(" Hello ,you will be a good code-man.\n"); printf("******************************\n"); }1-2.输入两个整数,输出它们的和,Sum#include<stdio.h>void main(){int a,b,s;int sum(int x,int y);printf("输入两个相加的整数:");scanf("%d%d",&a,&b);s=sum(a,b);printf("%d+%d=%d\n",a,b,s);}int sum(int x,int y){int r=x+y;return r;}1-3.输入3个整数,输出其最大的数max #include <stdio.h>void main(){int a,b,c,m;int max(int x,int y,int z);printf("输入求最大数的3个整数:"); scanf("%d%d%d",&a,&b,&c);printf("最大数max=%d\n",m);}int max(int x,int y,int z){int temp = x;if(temp<y) temp = y;if(temp<z) temp = z;return temp;}1-4.输入4个数,并由小到大的顺序输出sort #include <stdio.h>void main(){int a,b,c,d,temp;printf("请输入需要排序的4个整数:"); scanf("%d%d%d%d",&a,&b,&c,&d);if(a>b){temp = a;a = b;b = temp;}if(a>c){temp = a;a = c;c = temp;}if(a>d){temp = a;a = d;d = temp;}if(b>c){temp = b;b = c;c = temp;}if(b>d){temp = b;b = d;d = temp;}if(c>d){temp = c;c = d;d = temp;}printf("有小到大排序为:%d %d %d %d\n",a,b,c,d);}1-5.判断是否为闰年leapyear#include <stdio.h>void main (){int year,i=1;while(i)//用来循环使用函数!{printf("-------------------------------\n");printf("请输入需要判定的年份:");scanf("%d",&year);if((year%4==0&&year%100!=0)||(year%100==0printf("%d is a leapyear.\n",year);elseprintf("%d is not a leapyear.\n",year); printf("-------------------------------\n");}}1-6.输入一个华氏温度,要求输出摄氏温度,公式为C=5/9(F-32),取2位小数temper #include<stdio.h>void main(){float c,f;printf("请输入一个华氏温度:");scanf("%f",&f);c=(5.0/9.0)*(f-32);//注意5和9的值要用实数表示,否则5/9的值为0printf("摄氏温度为:%5.2f\n",c);}1-7.输入score,输出grade,Grade#include <stdio.h>void main(){float score;char grade;printf("请输入学生成绩:");scanf("%f",&score);while(score>100||score<0){printf("Error Data, please input new score:");scanf("%f",&score);}switch((int)(score/10)){case 10:case 9: grade = 'A';break;case 8: grade = 'B';break;case 7: grade = 'C';break;case 6: grade = 'D';break;default:grade = 'E';break;}printf("成绩是:%5.1f,相应的等级是:%c\n",score,grade); 1-8.用while、do..while、for循环语句写出n 的累加算法1+2+3…+n sum#include<stdio.h>void main(){void method_1(int x);void method_2(int y);void method_3(int z);int n,t=1;while(t){ printf("输入需要累加的值n:");scanf("%d",&n);printf("----------------------------------\n"); method_1(n);printf("----------------------------------\n"); method_2(n);printf("----------------------------------\n"); method_3(n);printf("----------------------------------\n");}}void method_1(int x){int s=0,i=1;while(i<=x){s=s + i;i++;}printf("#while循环累加%d = %d\n",x,s);}void method_2(int y){int i=1,s=0;do{s= s + i; i++; }while(i<=y);printf("#do...while循环累加%d = %d\n",y,s); }void method_3(int z){int s=0,i;for(i=1;i<=z;i++)s=s+i;printf("#for循环累加%d = %d\n",z,s);1-9.把100~200之间的不能被3整除的数输出扩:可以改写为输出同时被3和5整除的数continue语句使用#include<stdio.h>void main(){int n;for(n=100;n<=200;n++){if(n%3==0)continue;printf("%d ",n);}printf("\n");}扩:#include<stdio.h>void main(){int n;for(n=100;n<=200;n++){if(n%3!=0||n%5!=0)continue;printf("%d ",n);}printf("\n");}1-10.判断m是否素数prime number#include<stdio.h>#include<math.h>void main(){int m,i,k;printf("请输入需要判断是否为素数的数:"); scanf("%d",&m);k = sqrt(m);for(i=2;i<=k;i++)if(m%i == 0) break;if(i>k)printf("%d is a prime number\n",m); elseprintf("%d is not a prime number\n",m); } 1-11.求100~200间的全部素数prime#include<stdio.h>#include<math.h>void main(){int m,k,i,n=0;for(m=101;m<=200;m=m+2){ k=sqrt(m);for(i=2;i<=k;i++)if(m%i==0)break;if(i>=k+1){printf("%5d",m);n=n+1;}if(n%10==0)printf("\n");}printf("\n");}1-12.辗转相除法,输入两个正整数m和n,求其最大公约数和最小公倍数#include<stdio.h>void main(){int p,r,n,m,temp;printf("请输入两个正整数:");scanf("%d %d",&n,&m);if(n<m){temp=n;n=m;m=temp;}p=n*m;while(m!=0){r=n%m;n=m;m=r;}printf("它们的最大公约数为:%d\n",n); printf("它们的最小公倍数为:%d\n",p/n);1-13.打印1~1000中能被3整除的数,5个数字换一行输出printf#include<stdio.h>void main(){int i,j=0;for(i=1;i<=1000;i++){if(i%3==0){printf("%5d",i);j++;}if(j%5==0)printf("\n");}}1-14.输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数#include<stdio.h>void main(){char c;int letters=0,space=0,digit=0,other=0;printf("请输入一行字符:\n");while((c=getchar())!='\n'){if(c>='a'&&c<='z'||c>='A'&&c<='Z')letters++;else if(c==' ')space++;else if(c>='0'&&c<='9')digit++;elseother++;}printf("字母个数:%d\n空格个数:%d\n数字个数:%d\n其它字符个数:%d\n",letters,space,digit,other);}1-15.输出所有的水仙花数,水仙花数:一个3位数;各位数字立方和等于该数本身,如:153=1*1*1+5*5*5+3*3*3 narcissus num void main(){int i,j,k,n;printf("narcissus number are");for(n=100;n<1000;n++){i=n/100;j=n/10-i*10;k=n%10;if(n==i*i*i+j*j*j+k*k*k)printf("%5d",n);}printf("\n");}1-16.一个数如果恰好等于它的因子之和,则该数为“完数”,如6=1+2+3;要求输出1000以内的所有完数,并附带其因子一起输出#include<stdio.h>void main(){int m,s,i;for(m=2;m<1000;m++){s=0;for(i=1;i<m;i++)if((m%i)==0) s=s+i;if(s==m){printf("%d ,its factors are: ",m);for(i=1;i<m;i++)if(m%i==0) printf("%d ",i);printf("\n");}}}1-17.求S n=a+aa+aaa+…+aa…a之值,其中a 是一个数字。

c语言必背代码

c语言必背代码

c语⾔必背代码 1、/*输出9*9⼝诀。

共9⾏9列,i控制⾏,j控制列。

*/ #include"stdio.h" main() {inti,j,result; for(i=1;i<10;i++) {for(j=1;j<10;j++) { result=i*j; printf("%d*%d=%-3d",i,j,result);/*-3d表⽰左对齐,占3位*/ } printf("\n");/*每⼀⾏后换⾏*/ } } 2、/*古典问题:有⼀对兔⼦,从出⽣后第3个⽉起每个⽉都⽣⼀对兔⼦,⼩兔⼦长到第三个⽉后每个⽉⼜⽣⼀对兔⼦,假如兔⼦都不死,问每个⽉的兔⼦总数为多少? 兔⼦的规律为数列1,1,2,3,5,8,13,21....*/ main() { longf1,f2; inti; f1=f2=1; for(i=1;i<=20;i++) {printf("%12ld%12ld",f1,f2); if(i%2==0)printf("\n");/*控制输出,每⾏四个*/ f1=f1+f2;/*前两个⽉加起来赋值给第三个⽉*/ f2=f1+f2;/*前两个⽉加起来赋值给第三个⽉*/ } } 3、/*判断101-200之间有多少个素数,并输出所有素数及素数的个数。

程序分析:判断素数的⽅法:⽤⼀个数分别去除2到sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数。

*/ #include"math.h" main() { intm,i,k,h=0,leap=1; printf("\n"); for(m=101;m<=200;m++) {k=sqrt(m+1); for(i=2;i<=k;i++) if(m%i==0) {leap=0;break;} if(leap)/*内循环结束后,leap依然为1,则m是素数*/ {printf("%-4d",m);h++; if(h%10==0) printf("\n"); } leap=1; } printf("\nThetotalis%d",h); } 4、/*⼀个数如果恰好等于它的因⼦之和,这个数就称为"完数"。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

------------------------------------------------------------------------摘自宋鲁生程序设计大赛乘法口诀表#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();}学生成绩管理程序/*学生成绩管理程序编制一个统计学生考试分数的管理程序。

相关文档
最新文档