#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;
}
特定范围所有整数平方和(包含判断输入是否正确为整数)
最新推荐文章于 2023-02-22 16:51:44 发布
这篇博客主要介绍了如何使用C语言编写程序,首先判断用户输入是否为整数,然后计算该范围内所有整数的平方和。
4890

被折叠的 条评论
为什么被折叠?



