定义一个数组data,它包含100个double类型的元素。编写一个循环,将以下序列存储到数组的对应元素中:1/(2*3*4) 1/(4*5*6) 1/(6*7*8) 到1/(200*201*202)

本题为《C语言入门经典》第五章课后题。实际运行结果是一个圆周率pi的公式。所以这个习题可以叫计算圆周率。

#include<stdio.h>
int main(void)
{
	double data[100] = {0};	//Initialize array
	double temp = 0;	//Initialize calculation variable
	double temp_2 = 0;	//Initialize another calculation variable
	double num = 1.0;	//Store the multiplier
	/*calculate code*/
	for(unsigned i = 0 ; i < 100 ; ++i) //Calculates and stores the first array
	{
		num = (i+1) * 2;
		temp = 1 / (num * (num+1) * (num+2));
		data[i] = temp;
	}
	for(unsigned j = 0 ; j <100 ; ++j)	//Calculates and stores the second array
	{
		if((j % 2) == 0)	//Confirmation operation symbol
		{
			temp_2 += data[j];
		}
		else
		{
			temp_2 -= data[j];
		}
	}
	temp_2 = temp_2 * 4.0 + 3.0;
	printf("This is the final value:%lf",temp_2);
	return 0;
}

上一篇:读计算机考证


下一篇:papamelon 201. 部分和问题