预览加载中,请您耐心等待几秒...
1/5
2/5
3/5
4/5
5/5

在线预览结束,喜欢就下载吧,查找使用更方便

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

实验6循环结构程序设计 一.实验目的 掌握在设计条件型循环结构时,如何正确地设定循环条件。 掌握如何正确地控制计数型循环结构的循环次数。 练习并掌握选择结构与循环结构的嵌套、多重循环的应用。 掌握在程序设计中用循环的方法实现一些常用算法,加强调试程序的能力。 二.实验要求 复习while、do-while、for语句和continue、break语句。 能够用流程图表示实验题目的算法。 能够独立调试运行实验题目。 本实验要求4学时完成。 三.实验内容和步骤 题目1:分别用while循环和for循环计算:1+2+3+…+100=? 要求:写出程序并上机查看运行结果。 题目2:输入一行字符,分别统计出其中大小写英文字母、空格、数字和其他字母的个数。 要求:程序填空并写出2组运行结果。 #include<stdio.h> #include<conio.h> #include<ctype.h> main() { charc; intletter=0,capital=0,lower=0,space=0,digital=0,other=0; printf("\ninputalinecharacter:\n"); while((c=getchar())!='\n') { if(c>='a'&&c<='z'||c<='Z'&&c>='A')/*统计大小写字母的个数*/ { letter++; if(c>='a'&&c<='z') lower++;/*统计小写字母的个数*/ } elseif(c=='') space++;/*统计空格的个数*/ elseif(c>='0'&&c<='9') digital++;/*统计数字的个数*/ else other++;/*统计其他字符的个数*/ } capital=letter-lower; printf("Letter:%d(Capital:%dLowercase:%d)\n",letter,capital,lower); printf("Spaces:%d\nDigital:%d\nOther:%d\n",space,digital,other); getch(); } 题目3:求两个正整数的最大公约数和最小公倍数。 分析:求两个正整数的最大公约数采用辗转相除法: 输入正整数m和n,保证m不小于n; 如果n≠0,则求r=m%n,然后m=n,n=r;重复此操作直到n=0; 如果n=0,则此时m就是最大公约数,而最小公倍数是这两数之积除以这两数的最大公约数得到的商。 要求:程序填空并写出2组运行结果。 #include<stdio.h> #include<conio.h> main() { intm,n,r,a; printf("\nInput2positiveinteger:\n"); scanf("%d%d",&m,&n); a=n*m; if(m<n) { m=m+n; n=m-n; m=m-n; } while(n!=0) { r=m%n; m=n; n=r; } printf("Thelargestdivisoris:%d\n",m);/*输出最大公约数*/ printf("Thesmallestcommonmultipleis:%d\n",a/m);/*输出最小公倍数*/ getch(); } 题目4:在屏幕上打印出下三角的乘法表,如图6.1。试着完成下面的程序,并查看运行结果是否正确。 图6.1乘法表 #include<stdio.h> #include<conio.h> main() { inti,j; for(i=1;i<=9;i++) { for(j=1;j<=i;j++) printf("%d*%d=%-4d",i,j,j*i); printf("\n"); } getch(); } 题目5:在屏幕上打印出1000以内的素数,每行打印出10个,并统计个数。 要求:程序填空并写出运行结果。 #include<stdio.h> #include<conio.h> main() { inti,j,prime,s=0; for(i=2;i<=1000;i++) { prime=1; for(j=2;j<=i-1;j++) { if(i%j==0) { prime=0; break; } } if(prime==0) { printf("%6d",i); s++; if(s%10==0) printf("\n"); } } printf("\nThesumofprimeis:%d",s); getch(); } 题目6:打印出图6.2所示图案。 要求:程序填空并写出运行结果。 图6.2*号图案 #include<stdio.h> #include<conio.h> main()