详细代码如下:计算start到stop之间的平方和。
主程序只有一小部分,但输出sum_squares平方和一直为0?小白求帮助!
#include
#define true 1
#define false 0
long get_long(void);
int 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 squares of integers in a range.\n”
“The lower bound should no should not be more than -10000000 and\nthe upper bound ”
“should not be more than +10000000.\nEnter the limits (enter 0 for both limits to quit):\n”
“lower limit: “);
start = get_long();
printf(“upper limits: “);
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 “);
printf(“from %ld to %ld is %ld\n”,start,stop,answer);
}
printf(“Enter the lower 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())!=EOF)
putchar(ch);
printf(” is not an integer.\nPlease enter an “);
printf(“integer value,such as 25,-178,or 3: “);
}
return input;
}
double sum_squares(long a,long b)
{
double total = 0.0;
double i;
for(i=a;i<=b;i++)
total += i * i;
return total;
}
int bad_limits(long begin,long end,long low,long high)//输入验证.
{
int not_good=false;
if(begin>end)
{
not_good=true;
printf(“%ld isn”t smaller than %ld.\n”,begin,end);
}
if(beginhigh)
{
not_good=true;
printf(“Values must be %ld or great.\n”,low);
}
if(begin>high||end
{
not_good=true;
printf(“Values must be %ld or less.\n”,high);
}
return not_good;
}
解决方案
80
CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于while和scanf函数一起用的问题,读取的问题!