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

Posted abel2020

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
");
    printf("From -10000 To 10000.  Enter a range to computer. 
");
    printf("Input both 0 to Quit.
");

    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.
");
        else
        {
            answer = sum_square(start, stop);               //compute
            printf("   The sum of squares the integers from %d to %d is %g .
", start, stop, answer);
        }
        printf("Input both 0 to Quit.
");

    } 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()) != 
)            // ignore  Enter
            putchar(ch);

        printf(" is Not an integer. 
");
        printf(" Please Input a Number. 
");
    }
    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
", begin, end);
        not_good = true;                    // not good
    }
    if (begin < low || end < low)
    {
        printf("Iput must %ld or Lager.
", low);
        not_good = true;                    // not good
    }
    if (begin > high || end > high)
    {
        printf("Iput must %ld or Smaller.
", high);
        not_good = true;                    // not good
    }
    return not_good;
}

 

以上是关于11 计算a 和b 之间整数的平方和,模块化思想,输入检测的重要性的主要内容,如果未能解决你的问题,请参考以下文章

用python输入正整数N,计算1到N之间所以奇数的平方和,输出结果?

Leetcode 第56场双周赛 / 第249场周赛 / 1411. 给 N x 3 网格图涂色的方案数(这次主要还是学动规思想和迪杰斯克拉)

如何计算具有特定属性的大 A 和 B 之间的整数?

Python练习题2.11求平方与倒数序列的部分和

8.7 checking.c

0015---直角三角形求解