C语言自学路之计算平方(输入验证)

包含知识点:stdbool.h使用、自定义函数、多文件

检查用户输入是否是个整数,若不符合打印出并给予提示
若scanf()没有成功读取,就会将其留在输入队列中。这时候可以用getchar ( ) 函数逐字读取输入。

main.c 文件

/* 计算特定范围内所有整数平方和(-100^2 - 100^2)*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 100
#define MIN -100
long get_long(void);
bool text_limite(long putdown,long putup,long down,long up);
long sum_squares(long a ,long b);

int main()
{
    long start,stop;//最大值与最小值
    long answer;
    printf("This program computes the sum of the squares of integers in a range.\n");
    printf("The lower bound should not be less than -100.\nand the upper bound should ");
    printf("not be more than 100.\n(enter 0 for both limits to quit.)\n");
    printf("Please enter upper limit:");
    start=get_long();//验证输入是否有效并返回正确的值
    printf("Please enter lower limit:");
    stop=get_long();
    while(start!=0 || stop!=0)
    {
        if(text_limite(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 %ld.\n",start,stop,answer);
        }

    printf("(enter 0 for both limits to quit.)\n");
    printf("Please enter upper limit:");
    start=get_long();//验证输入是否有效并返回正确的值
    printf("Please enter lower limit:");
    stop=get_long();
    }
    printf("Bye.");
    return 0;
}


test_enter文件

long get_long(void)
{
    long input;
    char ch;
    while(scanf("%ld",&input)!=1)//成功读取用户输入的个数
    {
        while((ch=getchar())!='\n')
        //若scanf没有成功读取,就会将其留在输入队列中,就是用getchar()函数逐字读取
        putchar(ch);
    printf(" is not a integer.\nPlease enter another one.\n");
    }
    return input;
}

test_limite文件

/*测试范围区间大小*/
#include <stdio.h>
#include <stdbool.h>

bool text_limite(long putup,long putdown,long down,long upper)
{
    bool not_good=false;
    if(putup<putdown)
    {
        printf("%ld isn't smaller than %ld.\n",putup,putdown);
        not_good=true;
    }
    if(putup<down || putdown<down)
    {
        printf("Values must be %ld or greater.\n",down);
        not_good=true;
    }
    if(putup>upper || putdown>upper )
    {
        printf("Values must be %ld or less.\n",upper);
        not_good=true;
    }
    return not_good;
}

sumup 文件

/*求特定区间平方和*/
#include <stdio.h>

long sum_squares(long a ,long b)
{
    long total=0;
    long i;
    for(i=b;i<=a;i++)
    total+=i*i;

    return total;
}

更多推荐

C语言自学路之计算平方(输入验证)