特定范围所有整数平方和(包含判断输入是否正确为整数)

这篇博客主要介绍了如何使用C语言编写程序,首先判断用户输入是否为整数,然后计算该范围内所有整数的平方和。
#include<stdio.h>
#include<stdbool.h>

/*验证输入为一整数*/
long get_long(void)
{
	long input;
	char ch;

	while (scanf("%ld",&input) != 1)/*输入不是整数*/
	{
		while ((ch = getchar()) != '\n')
		{
			putchar(ch);/*输出错误的输入*/
		}
		printf(" is not an integer.\nPlease enter an integer value,such as 25,-178,or 3: ");
	}
	return input;
}

/*验证范围上下限是否有效*/
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;
}

/*计算整数平方和*/
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;
}

/*主程序*/
int main(void)
{
	const long MIN = -100000000;/*范围下限*/
	const long MAX = +100000000;/*范围上限*/
	long start;/*指定范围最小值*/
	long stop;/*指定范围最大值*/
	double answer;

	printf("This program computes the sum of the squares of integers in a range.\n"
			"The lower bound should not be less than %ld and the upper bound should not be more than %ld.\n "
			"Enter the limits(Enter o for both limits to quit):\n"
			"lower limit: ",MIN,MAX);
	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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值