C PRIMER +的验证程序实例(C8程序清单8.7)

本文介绍了一个使用C语言编写的程序,该程序能够计算指定范围内所有整数的平方之和,并验证输入范围的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习备份用~

#include <stdio.h>
#include <stdbool.h>
long get_long(void);
bool bad_limits(long begin, long end, long low, long high);
double sum_squares(long a, long b);
int main(void)
{
    const long MIN = -10000000L;
    const long MAX = +10000000L;
    long start;
    long stop;
    double answer;
    printf("This program computes the sum of the square of"
            "integers in a range.\nThe lower bound should not "
            "Be less than -10000000 and\n the upper bound should"
            " not be more than +10000000.\nEnter the limits (enter 0 for both limits to quit):\n");
    printf("Lower limit:");
    start = get_long();
    printf("Upper limit:");
    stop = get_long();
    while(start !=0 || stop != 0)
    {
        if (bad_limits(start, stop, MIN, MAX))
            printf("Please try again:\n");
        else
        {
            answer = sum_squares(start, stop);
            printf("The sum of the squares of the integers 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);
        printf("is not an integer.\n Please enter an integer value,such as 25,-178 or 3:");
    }

    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 bad_limits(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值