case5:rate=5.0*2.88*0.01 default: printf ("Input Error\n") rest=benjinkrate printf("benjin: %10. 2lf \n", benjin printf(" rate: %10. 5lf\n", rate) printf(" total: %10. 2lf\n", total) 3.18“水仙花数”是指一个三位数,它的三个数位数字的立方和这个数的数值相等, 编程打印所有的水仙花数 解:本题适于使用穷举法求解,注意穷举范围为三位数100~99,穷举条件为:三位数的 三个数位数字的立方和等于这个数的数值。需要使用循环结构。程序如下: #include <stdio. h main t do d1 d2. n printf( The numbers are " for(n=100;n<=999;n++) do=n%10 d1=n%100/10 f(n=d0*d0*d0+d1*d1*d1+d2*d2*d2) printf(%5d", n) printf( "\n") 3.19编写程序,统计C源程序中标识符的个数 解:程序的关键是如何判断标识符。由标识符定义知它由字母、数字和下划线组成且第 个字符不能是数字。 inword变量记录当前字符的状态, inword==1表示当前字符在标识符 内, inword==0表示当前字符不在标识符内, Unquote变量记录当前字符是否在引号内(设 不考虑引号嵌套的情况),本题只能由键盘输入若干行源程序。参考程序如下 #include <stdio. h> I int c, num, inquota=0, inword=0
case 5: rate=5.0*2.88*0.01; break; default: printf("Input Error\n"); exit(0); } rest=benjin*rate; total=benjin+rest; printf("benjin: %10.2lf\n",benjin); printf(" rate: %10.5lf\n",rate); printf(" total: %10.2lf\n",total); } 3.18 “水仙花数”是指一个三位数,它的三个数位数字的立方和这个数的数值相等, 编程打印所有的水仙花数。 解:本题适于使用穷举法求解,注意穷举范围为三位数 100~999,穷举条件为:三位数的 三个数位数字的立方和等于这个数的数值。需要使用循环结构。程序如下: #include <stdio.h> main() { int d0,d1,d2,n; printf("The numbers are :"); for (n=100;n<=999;n++) { d0=n%10; d1=n%100/10; d2=n/100; if (n==d0*d0*d0+d1*d1*d1+d2*d2*d2) printf("%5d",n); } printf("\n"); } 3.19 编写程序,统计 C 源程序中标识符的个数。 解:程序的关键是如何判断标识符。由标识符定义知它由字母、数字和下划线组成且第一 个字符不能是数字。inword 变量记录当前字符的状态,inword==1 表示当前字符在标识符 内,inword==0 表示当前字符不在标识符内,inquota 变量记录当前字符是否在引号内(设 不考虑引号嵌套的情况),本题只能由键盘输入若干行源程序。参考程序如下: #include <stdio.h> main() { int c,num,inquota=0,inword=0;
while ((c=getchar O)!=EOF if((c=V)|(c=2\")) I if (inquota=1) else inquota=l else if(!((o>='a')&(c<=z)川(c>=’A')&(c<=Z) (c>=’03)&&(c<=9)(c=’) I if ((inword==1)&&(inquota=0)) else if((inword==0)&&(inquota==0)) if(!((c>=0)&&(c<=9’)) word=1 1/* whle * printf("num%d\n", num) 3.20编程计算1!+2!+3!+…+n!,验证对前10项求得的结果是否正确?当n=20 时,结果是否正确?如果出错,弄清原因,并修改程序。 解:本题需要考虑数据计算可能溢出的问题,累计阶乘计算结果的变量值增长很快,应该 考虑使用表示范围更大的数据类型(long、floa或 double)。程序需要循环结构,注意当 前项的计算方法,参考程序如下: #include <stdio. h main i long s=0, t=1 int printf( Enter integer n scanf(%d", &n) for(i=;i<=n;i++ t*=i; printf("s=%ld\n", s)
num=0; while ((c=getchar())!=EOF) { if ( (c=='\'')||(c=='\"') ) { if (inquota==1) inquota=0; else inquota=1; } else if ( !(((c>='a')&&(c<='z'))||((c>='A')&&(c<='Z')) ||((c>='0')&&(c<='9'))||(c=='_')) ) { if ((inword==1)&&(inquota==0)) {inword=0; num++; } } else if ( (inword==0)&&(inquota==0)) { if (!((c>='0')&&(c<='9'))) inword=1; } } /* whle */ printf("num=%d\n",num); } 3.20 编程计算 1!+2!+3!+···+n!,验证对前 10 项求得的结果是否正确?当 n=20 时,结果是否正确?如果出错,弄清原因,并修改程序。 解:本题需要考虑数据计算可能溢出的问题,累计阶乘计算结果的变量值增长很快,应该 考虑使用表示范围更大的数据类型(long 、float 或 double)。程序需要循环结构,注意当 前项的计算方法,参考程序如下: #include <stdio.h> main() { long s=0,t=1; int i,n; printf("Enter integer n:"); scanf("%d",&n); for (i=1;i<=n;i++) { t*=i; s+=t; } printf("s=%ld\n",s); }