微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用函数验证输入

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

long get_long(void);
bool isWrongInput(long begin, long end,long low, long high);

double sum_squares(long a, long b);

int main(void)
{
    const long MIN = -10000000L;  // lower limit to range
    const long MAX = +10000000L;  // upper limit to range
    long start;                   // start of range
    long stop;                    // end of range
    double answer;
    //from   w  w  w  .  j  av a  2 s .c  om
    printf(Enter the limits (0 to quit)lower limit\n: );
    start = get_long();
    printf(upper limit: );
    stop = get_long();
    while (start !=0 || stop != 0)
    {
        if (isWrongInput(start, stop, MIN, MAX))
            printf(Please try again.\n);
        else
        {
            answer = sum_squares(start, stop);
            printf(The sum of the squares of the integers );
            printf(from %ld to %ld is %g\n, start, stop, answer);
        }
        printf(Enter the limits (enter 0 for both  limits to quit):\n);
        printf(lower limit: );
        start = get_long();
        printf(upper limit: );
        stop = get_long();
    }
    printf(Done.\n);

    return 0;
}

long get_long(void)
{
    long input;
    char ch;

    while (scanf(%ld, &input) != 1)
    {
        while ((ch = getchar()) != '\n')
            putchar(ch);  // dispose of bad input
        printf( is not an integer.\n);
    }

    return input;
}

double sum_squares(long a, long b)
{
    double total = 0;
    long i;

    for (i = a; i <= b; i++)
        total += (double)i * (double)i;

    return total;
}

bool isWrongInput(long begin, long end,
                long low, long high)
{
    bool not_good = false;

    if (begin > end)
    {
        printf(%ld isn't smaller than %ld.\n, begin, end);
        not_good = true;
    }
    if (begin < low || end < low)
    {
        printf(Values must be %ld or greater.\n, low);
        not_good = true;
    }
    if (begin > high || end > high)
    {
        printf(Values must be %ld or less.\n, high);
        not_good = true;
    }

    return not_good;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐