码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-05-27 12:14:30      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:整数   std   The   etc   重要性   主程序   lse   clu   lower   

// 计算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;
}

 

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

标签:整数   std   The   etc   重要性   主程序   lse   clu   lower   

原文地址:https://www.cnblogs.com/abel2020/p/12971509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!