计算指定范围的平方和(含错误处理)

本文介绍了一个使用C语言编写的程序,该程序可以计算用户指定范围内所有整数的平方和。程序首先检查输入的范围是否合法,然后调用函数计算平方和,并将结果输出。
   #include <stdio.h>
   #include <stdbool.h>
   
   double sum_squares(long a, long b);//计算指定范围的平方和
   bool bad_limits(long begin, long end, long low, long high);//判断上界及下界
   long get_long(void);//判断输入是否是整数
   
   int main(void) {
   	const long MAX = 100000l;
   	const long MIN = -100000l;
   	long lower;
   	long upper;
   	double sum;
   
   	printf("This program computes the sum of the squares of integers in a range.\n");
   	printf("The lower bound should not be less than -100000 and\n");
   	printf("the upper bound should not be more than 100000.\n");
   	printf("Enter the limits (enter 0 for both limits to quit):\n");
   	printf("lower limit: ");
   	lower = get_long();//取得下界
   	printf("upper limit: ");
   	upper = get_long();//取得上界
   	while (lower != 0 || upper != 0) {//判断结束标志
   		if (bad_limits(lower, upper, MIN, MAX))//范围错误处理
   			printf("Please try again.\n");
   		else {
   			sum = sum_squares(lower, upper);
   			printf("The sum of the squares of the integers from %ld to %ld is %ld.\n",
   				lower, upper, (long)sum);
   		}
   		printf("Enter the limits (enter 0 for both limits to quit):\n");
   		printf("lower limit: ");
   		lower = get_long();
   		printf("upper limit: ");
   		upper = get_long();
   	}
   	printf("Done.");
   	return 0;
   }
   
   long get_long(void) {
   	long a;
   	char ch;
   	while (!scanf("%ld", &a)) {//输入的不是整数
   		while ((ch = getchar()) != '\n') {//清除错误结果
   			putchar(ch);
   		}
   		printf(" is not an integer.\n");//打印错误与提示信息
   		printf("Please enter an integer value, such as 25, -178, or 3: ");
   	}
   	return a;//返回整数值
   }
   
   bool bad_limits(long begin, long end, long low, long high) {
   
   	if (begin > end) {//范围出错处理
   		printf("%ld isn't smaller than %ld.\n",begin,end);
   		return true;
   	}
   	else{//溢出处理
   		if (begin < low) {
   			printf("%ld is too small!!\n",begin);
   			return true;
   		}
   		if (end > high) {
   			printf("%ld is too big!!\n",end);
   			return true;
   		}
   	}
   	return false;
   }
   
   double sum_squares(long a, long b) {
   	double sum = 0;
   	for (; a <= b; a++)
   		sum += a * a;
   	return sum;
   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值