资源描述:
《C语言简单地23个例子》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、实用标准文案例1.1:输入两个数,输出其中的最大者方法一:#include"stdio.h"intmain(){inta,b,max;scanf("%d%d",&a,&b);if(a>b)max=a;elsemax=b;printf("%d",max);return0;}方法二:#include"stdio.h"intmain(){intm,n;scanf("%d%d",&m,&n);printf("%d",(m>n)?m:n);return0;}例1.2:输入三个数,输出其最大者#include"stdio.h"intmain(){inta,b,c;scanf("
2、%d%d%d",&a,&b,&c);printf("%d",a>b?(a>c?a:c):(b>c?b:c));return0;}例2:求一个数的绝对值方法一:#include"stdio.h"intmain(){inta,absa;printf("enteronenumber:");scanf("%d",&a);if(a<0)absa=-a;文档大全实用标准文案elseabsa=a;printf("
3、%d
4、=%d",a,absa);return0;}方法二:#include"stdio.h"#include"math.h"intmain(){inta;scanf
5、("%d",&a);printf("%d",abs(a));return0;}例3:两个数的四则运算#include"stdio.h"intmain(){doublex,y;charop;printf("输入运算式:");scanf("%lf%c%lf",&x,&op,&y);switch(op){case'+':printf("%.2f%c%.2f=%.2f",x,op,y,x+y);break;case'-':printf("%.2f%c%.2f=%.2f",x,op,y,x-y);break;case'*':printf("%.2f%c%.2f=%.2
6、f",x,op,y,x*y);break;case'/':if(y==0)printf("error!");elseprintf("%.2f%c%.2f=%.2f",x,op,y,x/y);break;default:printf("expressioniserror!");}return0;}例4:求N个数的平均数,以-1结束输入,且-1不纳入计算文档大全实用标准文案#include"stdio.h"intmain(){intn=0;doublea,sum=0;while(1){scanf("%lf",&a);if(a==-1)break;sum+=a;n
7、++;}printf("%.2f",sum/n);return0;}例5:打印出九九乘法口诀#include"stdio.h"intmain(){inti,j;for(i=1;i<10;i++){for(j=i;j<10;j++){printf("%dx%d=%-4d",i,j,i*j);}printf("");}return0;}例6:大小写转换,以数字0结束输入#include"stdio.h"intmain(){charch;while(1){scanf("%c",&ch);if(ch=='0')break;if(ch>='A'&&ch<='Z')printf
8、("%c",ch+32);if(ch>='a'&&ch<='z')printf("%c",ch-32);文档大全实用标准文案}return0;}例7:打印菱形图案#include"stdio.h"intmain(){inti,j,k;for(i=0;i<10;i++){for(j=0;j<=9-i;j++)printf("");for(k=0;k<=2*i;k++)printf("%c",3);printf("");}for(i=0;i<=9;i++){for(j=0;j<=i+1;j++)printf("");for(k=0;k<=16-2*i;k++)pri
9、ntf("%c",3);printf("");}return0;}例8:求100以内所有的素数#include"stdio.h"#include"math.h"main(){intm,i,k,t=0,j=1,n=0;printf("%3d:",j);for(m=2;m<=300;m=m+1){k=(int)sqrt(m);for(i=2;i<=k;i++)if(m%i==0)break;if(i>=k+1){printf("%5d",m);文档大全实用标准文案t++;if(t%4==0)printf("%3