本题要求编写程序,计算序列部分和 1 - 1/4 + 1/7 - 1/10 + ... 直到最后一项的绝对值不大于给定精度eps。
输入格式:
输入在一行中给出一个正实数eps。
输出格式:
在一行中按照“sum = S”的格式输出部分和的值S,精确到小数点后六位。题目保证计算结果不超过双精度范围。
The standard solution of the book:
Marked by B:
int main(void)
{
int denominator,flag;
double esp,item,sum;
scanf("%f",&esp);
flag=1;
denominator=1;
sum=0;
item=1.0;
do
{
item=flag*1.0/denominator;
sum=sum+item;
flag=-flag;
denominator=denominator+3;
}while(fabs(item)>esp);
printf("sum = %.6f\n",sum);
}
Something I wrote:
Marked by A :
int main()
{
double eps;
scanf("%lf",&eps);
double sum=0;
int i=0;
while(1.0/(3*i+1)>=eps)
{
sum+=pow(-1,i)*1.0/(3*i+1);
i++;
}
printf("sum = %.6lf",sum);
}
Two different series of codes, and you are smart enough to find the difference quickly—one uses the loop of "while" while another uses the loop of " do while". And this is because two different understanding concerning the title: Does the last item include the primary item?
But the real pony here is that if you amend the former codes into the following one-C:
Marked by C:
int main()
{
double eps;
scanf("%lf",&eps);
double sum=0;
int i=0;
do
{
sum+=pow(-1,i)*1.0/(3*i+1);
i++;
}while(1.0/(3*i+1)>=eps);
printf("sum = %.6lf",sum);
return 0;
}
C is not equal to B.
And something interesting is they both pass the PTA's test!
I hope somebody can tell me the difference that I don't know about them. Thank you!