每当我们进行输入的时候,我们都要想到是否需要处理剩余的垃圾输入,从而让它们不会影响到我们的后续输入!尤其是gechar和“回车符”一起使用的时候!
- #include<stdio.h>
- #define MAX 1000
- #define MIN -1000
- bool bad_limits(int start,int end,int low,int high);
- int get_int();
- double answer(int start,int end);
- int main(void){
- int start;
- int end;
- double result;
- do{
- printf("Please Enter the start (EOF to quit)\n");
- start = get_int();
- printf("Please Enter the end (EOF to quit)\n");
- end = get_int();
- if(bad_limits(start,end,MIN,MAX)){
- printf("Please try again!\n");
- continue;
- }
- else{
- result = answer(start,end);
- printf("The answer is %lf\n",result);
- }
- }while(start !=0 || end != 0);
- printf("Bye\n");
- return 0;
- }
- int get_int(){
- int input;
- char ch;
- while(scanf("%d",&input) != 1){ //如果输入有问题
- while((ch = getchar()) != '\n'){ //丢弃该行中的所有输入
- putchar(ch);//并将这些垃圾值显示出来
- }
- printf(" is not an integer.\n");
- }
- return input;
- }
- double answer(int start,int end){
- double total = 0;
- int i;
- for(i=start;i<=end;i++){
- total += i * i;
- }
- return total;
- }
- bool bad_limits(int start,int end,int low,int high){
- bool not_good = false;//设置标记位
- if(start > end){
- printf("start too big!\n");
- not_good = true;
- }
- if(start <low || end >high){
- printf("another problem!\n");
- not_good = true;
- }
- return not_good;
- }