2013年4月2日 星期二

[C]book page 203 problem 3 solution

//Method 1
	int i=1,j=2,n=0;
	double odd_result=0,even_result=0,result;
	double temp=0;
	printf("Please enter the number of n.\n");
	printf("The number of n is lager the value, the more accruate the result\n");
	printf("input n >");
	scanf("%d",&n);
	//Calculate odd term
	while(i < n)
	{
		temp=1.0/(2*i-1);
		odd_result=odd_result+temp;
		i=i+2;
	}
	//Calculate even term
	while(j < n+1)
	{
		temp=1.0/(2*j-1);
		even_result=even_result+temp;
		j=j+2;
	}
	//The result
	printf("(odd,even)=(%.16f,%.16f)\n",odd_result,even_result);
	result=odd_result-even_result;
	printf("The calculate result is %.16f\n",result);
//Method 2
	int i=1,n=0;
	double result=0,temp=0;
	printf("Please enter the number of n.\n");
	printf("The number of n is lager the value, the more accruate the result\n");
	printf("input n >");
	scanf("%d",&n);
	//Calculate
	while(i < n)
	{
		if(i%2 == 0)
		{
			temp=1.0/(2*i-1);
			result=result-temp;
		}
		else
		{
			temp=1.0/(2*i-1);
			result=result+temp;
		}
		i++;
		printf("Now, n = %10d,the result is %.16f\n",i,result);
	}

沒有留言:

張貼留言