程序清单8.7 使用两个函数来向一个算术函数传送整数,该函数计算特定范围内全部整数的平方和。程序限制这个特定范围的上界不该该超过1000,下界不该该小于-1000。编程
/*checking.c --输入确认*/ #include <stdio.h> #include <stdbool.h> //确认输入了一个整数 int get_int(void); //确认范围的上下界是否有效 bool bad_limits (int begin,int end,int low,int high); //计算从a到b之间的整数的平方和 double sum_squares(int a,int b); int main (void) { const int MIN = -1000; //范围的下界限制 const int MAX = +1000; //范围的上界限制 int start; //范围的下界 int stop; //范围的上界 double answer; printf("This program computes the sum of the squares of " "integers in a range.\nThe lower bound should not " "be less than -1000 and \nthe upper bound should not " "be more than +1000.\nEnter the limits (enter 0 for " "both limits to quit):\nlower limit: "); //注意printf()的换行方式 start = get_int(); printf("upper limit:"); stop = get_int(); while(start!=0 || stop!=0) { if(bad_limits(start,stop,MIN,MAX)) printf("please try again.\n"); else { answer = sum_squares(start,stop); printf("The sum of the squares of the integers from "); printf("from %d to %d is %g\n",start,stop,answer); } printf("Enter the limits (enter 0 for both limits to quit): \n"); printf("lower limit: "); start = get_int(); printf("upper limit: "); stop = get_int(); } printf("Done.\n"); return 0; } int get_int (void) { int input ; char ch; while(scanf("%d",&input)!=1) { while((ch=getchar())!='\n') putchar(ch); //剔除错误的输入 printf(" is not an integer .\nPlease enter an "); printf("integer value ,such as 25, -178, or 3: "); } return input; } double sum_squares (int a ,int b) { double total = 0; int i ; for(i=a;i<=b;i++) total += i*i; return total; } bool bad_limits(int begin,int end,int low,int high) { bool not_good = false; if(begin>end) { printf("%d isn't smaller than %d.\n",begin,end); not_good=true; } if(begin<low || end<low) { printf("Values must be %d or greater.\n",low); not_good = true; } if(begin>high || end>high) { printf("Values must be %d or less.\n",high); not_good = true; } return not_good; }
8.6.1 分析程序less
首先集中讨论程序的总体结构。模块化
咱们已经遵循了一种模块化的方法,使用独立的函数(模块)来确认输入和管理显示。程序越大,使用模块化的方法进行编程就越重要。函数
main()函数管理流程,为其余函数指派任务。它使用get_int()来获取值,用while循环来处理这些值,用bad_limits()函数来检查值的有效性,sum_squares()函数则进行实际的计算;ui
8.6.2 输入流和数值编码
考虑以下输入 :code
is 28 12.4字符串
在您的眼中,该 输入是一串字符后面跟着一个整数,而后是一个浮点值。对C程序而言,该 输入 是一个字节流。第一个字节是字母i的字符编码,第二个字节是字母s的字符编码,第三个字节是空格字符的字符编码,第四个字节是数字2的字符编码,等等。因此若是get_int()遇到这一行,则下面的代码将读取并丢弃整行,包括数字,由于这些数字只是该行中的字符而已:get
while((ch=get())!='\n') putchar(ch);input
虽然输入流由字符组成,但若是您指示了scanf()函数,它就能够将这些字符转换成数值。例如,考虑下面的输入:
42
若是您在scanf()中使用%c说明符,该函数将只读取字符4并将其存储在一个char类型的变量中。若是您使用%s说明符,该 函数会读取两个字符,即字符4和字符2,并将它们存储在一个字符串中。若是使用%d说明 符,则scanf()读取一样的两个字符,可是随后它会继续计算与它们相应的整数值为4X10+2,即42而后将该 整数的二进制表示保存在一个int 变量中。若是使用%f说明符,则scanf()读取这两个字符,计算它们对应的数值42,而后之内部浮点表示法表示该 值,并将结果保存在一个float变量中。
简言之,输入由字符组成,但scanf()能够将输入转换成整数或浮点值。使用像%d或%f这样的说明符能限制可接受的输入的字符类型,但getchar()和使用%c的scanf()接受任何字符。