11 计算a 和b 之间整数的平方和,模块化思想,输入检测的重要性

// 计算a 和b 之间整数的平方和
// 模块化,主程序做流程控制,1个计算函数,1个输入合法函数,1个范围检测函数

#include <stdio.h>
#include<stdbool.h>

double sum_square(long a, long b);
bool bad_limit(long begin, long end, long low, long high);
long get_long(void);

main() {
    const long MIN = -10000L;        //  low limit
    const    long MAX = 10000L;      //  high limit
    long start;                      //  lower input
    long stop;                       //  upper iput
    double answer;                   //  computes   sum of integers

    //Note:
    printf("This progam is computer the sum of the squres of a ranger.\n");
    printf("From -10000 To 10000.  Enter a range to computer. \n");
    printf("Input both 0 to Quit.\n");

    do {
        printf("Input the Start: ");
        start = get_long();              // check and assign
        printf("Input the End:  ");
        stop = get_long();               // check and assign

        if (bad_limit(start, stop, MIN, MAX))               // check  range
            printf("Please Input Again.\n");
        else
        {
            answer = sum_square(start, stop);               //compute
            printf("   The sum of squares the integers from %d to %d is %g .\n", start, stop, answer);
        }
        printf("Input both 0 to Quit.\n");

    } while (start != 0 || stop != 0);                      // input 0 to quit

    printf("Done, Bye bye !!!");
}

//compute  prog
double sum_square(long a, long b) {
    double total = 0;
    long i;
    for (i = a;i <= b;i++) {
        total += (double)i * (double)i;
    }
    return total;
}

//get input
long get_long(void) {
    long input;
    char ch;
    while (scanf_s("%ld", &input) != 1) {           //check input is a num
        while ((ch = getchar()) != '\n')            // ignore  Enter
            putchar(ch);

        printf(" is Not an integer. \n");
        printf(" Please Input a Number. \n");
    }
    return input;
}

// check if or Not  in the rang
bool bad_limit(long begin, long end, long low, long high)
{
    bool not_good = false;                  //default   is  good
    if (begin > end)
    {
        printf("%ld is Not smaller than %ld\n", begin, end);
        not_good = true;                    // not good
    }
    if (begin < low || end < low)
    {
        printf("Iput must %ld or Lager.\n", low);
        not_good = true;                    // not good
    }
    if (begin > high || end > high)
    {
        printf("Iput must %ld or Smaller.\n", high);
        not_good = true;                    // not good
    }
    return not_good;
}

 

posted @ 2020-05-27 11:27  abel2020  阅读(148)  评论(0编辑  收藏  举报