C语言经典题目:求阶乘n!=n*(n-1)*...*1,阶乘和s=1!+(2)!+(3)!+...+n!

1.求阶乘n!=n*(n-1)*...*1

思路:利用递推,迭代;

找规律:f(1)=1;f(2)=2*1;f(3)=3*2*1=3*(f(2));

一般公式:f(n)=n*f(n-1)

float fac(int n)
{
	//求n!=n*(n-1)*...*1;
	if (n == 1 || n == 0)
	{
		return 1;
	}
	return n * fac(n - 1);
}

2.计算s=1!+(2)!+(3)!+...+n!

float getfac_s(int n)
{
	//计算s=1!+(2)!+(3)!+...+n!
	float fac(int n);//声明
	float sum = 0;
	int i;
	for (i = 1; i <= n; i++)
	{
		sum += fac(i);
	}
	return sum;
}

3.s=n!+(n+1)!+(n+2)!+...+m!


float getfac_s(int m, int n)
{
	//计算s=n!+(n+1)!+(n+2)!+...+m!
	int i;
	float s = 1, sum = 0;
	for (i = 1; i <= m; i++)
	{
		s = s * i;
		if (i >= n)
		{
			sum += s;
		}
	}
	return sum;
}

4.求分式e=1+1/1!+1/2!+...+1/n!

float getfac_e(int n) {
	//分式求值,记得要用浮点型
	//e=1+1/1!+1/2!+...+1/n!;
	int i;
	float e = 1, t;//项
	for (i = 1; i <= n; i++)
	{
		t = float(1.0) / fac(i);
		e += t;
	}
	return e;
}

 

你可能感兴趣的:(C语言)