C language test | Question: Input 1 positive integer n, calculate the sum of the first n reciprocal factorials of s

Question content : Input positive integer n and calculate the sum of the first n terms of  s  .

s = 1 + 1/2! +....+ 1/n!

Method 1: [Two for loops]

double fun(int n)
{
	double s = 1.0,s_ = 1.0;
	int i,m;
	for(i=1;i<=n;i++)
	{
		s_ = 1.0;
		for(m=1;m<=i;m++)
		{
			s_ = s_ * m;
			printf("%lf\n",s_);
		}
		s = s +  (1.0/s_);
	}

	return s;
}
void main()
{
	int n;
	printf("input n:");
	scanf("%d",&n);
	printf("s = %f\n",fun(n));
	system("pause");
}

 Method 2: [One for loop]

double fun(int n)
{
	double temp = 1;
	double s = 1;
	for(int i=1;i<=n;i++)
	{
		temp /= i;
		s += temp;
	}
	return s;
}
void main()
{
	int n;
	printf("input n:");
	scanf("%d",&n);
	printf("s = %f\n",fun(n));
	system("pause");
}

Guess you like

Origin blog.csdn.net/zzztutu/article/details/126365026