數學上相等的變換,計算機似乎不一定

本題要求編寫程序,計算序列部分和 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! 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章