资源描述:
《C语言答案第4章》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、第4章4.1分析下面程序的结果:(1)#includevoidmain(){inti,t,sum=0;for(t=i=1;i<=10;){sum+=t;++i;if(i%3==0)t=-i;elset=i;}printf("sum=%d",sum);}运行结果:sum=19分析:该数列为sum=1+2-3+4+5-6+7+8-9+10(2)#includevoidmain(){inti;for(i=1;i<=5;i++){switch(i%2){case0:i++;printf("#");break;case1:i+=2
2、;printf("*");default:printf("");}}printf("i=%d",i);}运行结果:*#i=6(3)#includevoidmain(){inty=10;do{y--;}while(--y);printf("%d",y--);}运行结果:0分析:循环体共执行5次(4)#includevoidmain(){intm,n;printf("Enterm,n;");scanf("%d%d",&m,&n);while(m!=n){while(m>n)m-=n;while(n>m)n-=m;}p
3、rintf("m=%d",m);}运行结果:m=14.2求自然数1~100的累加和,分别用三种循环控制语句实现。方法1(for循环)#includevoidmain(void){inti,sum=0;for(i=0;i<=100;i++)sum+=i;printf("%d",sum);}方法2(while循环)#includevoidmain(void){inta=1,sum=0;while(a<=100){sum+=a;a++;}printf("%d",sum);}方法3(do-while循环)#include4、tdio.h>voidmain(void){inti,sum=0;i=1;do{sum=sum+i;i++;}while(i<=100);printf("%d",sum);}4.3计算1-3+5-7+…-99+101的值。解1:#includevoidmain(){inti,t=1,s=0;for(i=1;i<=101;i=i+2){t=t*i;s=s+t;t=-t/i;}printf("%d",s);}解2:#include#includevoidmain(){intn,t,pi,s;s=t=n=1;p
5、i=0;for(n=1;n<=101;){pi=pi+t;n=n+2;s=-s;t=s*n;}printf("PI=%d",pi);}4.4根据公式,求e的近似值,精度要求为10-6。#includevoidmain(){inti;doublee,f;e=1.0;f=1.0;for(i=1;f>=1e-6;i++){f/=(double)i;e+=f;}printf("e=%f",e);}4.5用公式:求∏的近似值,直到最后一项的值小于10-6为止。#include#includevoidmain
6、(){longi=1;doublepi=0;while(i*i<=10e+6){pi=pi+1.0/(i*i);i++;}pi=sqrt(6.0*pi);printf("pi=%10.6lf",pi);}4.6编写程序,求下面和式的值。#includevoidmain(){doubles=0,t=1;intn;for(n=1;n<=20;n++){t=t*n;s=s+t;}printf("1!+2!+…+20!=%e",s);}4.7将从键盘输入的一对数,由小到大排序输出。当输入一对相等数时结束循环。#include7、h>voidmain(){inta,b,t;scanf("%d,%d",&a,&b);while(a!=b){if(a>b){t=a;a=b;b=t;}printf("%d,%d",a,b);scanf("%d,%d",&a,&b);}}4.8从键盘输入的一组字符中统计出大写字母的个数m和小写字母的个数n,并输出m、n中的较大者。#includevoidmain(){intm=0,n=0;charc;while((c=getchar())!=''){if(c>'A'&&c<='Z')m++;if(c>='a'&&c<='z')n+
8、+;}printf("m=%d,n=%d,max=%d",m,