c语言求阶乘的函数

nt fac(int n) {static int f=1; f=f*n;i<=5;i++) printf("%d!=%d\n" return(f); } main() {int i; for(i=1

  阶乘:
  阶乘是基斯顿·卡曼(Christian
Kramp,1760~1826)于
1808
年发明的运算符号,是数学术语。
  一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1。自然数n的阶乘写作n!。1808年,基斯顿·卡曼引进这个表示法。
  亦即n!=1×2×3×...×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。
  
  C语言
  在
C
语言中,使用循环语句可以很方便的求出阶乘的值,下面介绍一个很简单的阶乘例子。(因为网上多数是比较麻烦的方法)
  【计算出“
1!+
2!+
3!+
……
+
10!”的值是多少?】
  #include<stdio.h>
  int
main()
  {
  int
x;
  long
j=1,sum=0;
  for(x=1;x<=10;x++)
  {
  j*=x;
  sum+=j;
  }
  printf("1!+2!+...+10!=%ld\n",sum);
  return
0;
  }
  
  /*结果:4037913*/
  Pascal中program
test;
  varn:longint;
  function
jc(n:longint):qword;
  begin
if
n=0
then
jc:=1
else
jc:=n*jc(n-1)end;
  begin
readln
(n);
writeln
(jc(n))end.
  C++

  #include<iostream>
  using
namespace
std;
  long
long
f(int
n)
  {
  long
long
e=1;
  if(n>0)
  e=n*f(n-1);
  cout<<n<<"!="<<e<<endl;
  return
e;
  }
  int
main()
  {
  int
m=20;
  f(m);
  return
0;
  }
  
  以上使用
C++
11
标准
  也可以利用积分求浮点数阶乘:
  #include<cstdio>
  #include<cmath>
  double
s;
  const
double
e=exp(1.0);
  double
F(double
t)
  {
  return
pow(t,s)*pow(e,-t);
  }
  double
simpson(double
a,double
b)
  {
  double
c=a+(b-a)/2;
  return
(F(a)+4*F(c)+F(b))*(b-a)/6;
  }
  double
asr(double
a,double
b,double
eps,double
A)
  {
  double
c=a+(b-a)/2;
  double
L=simpson(a,c),R=simpson(c,b);
  if(fabs(L+R-A)<=15*eps)
return
L+R+(L+R-A)/15.0;
  return
asr(a,c,eps/2,L)+asr(c,b,eps/2,R);
  }
  double
asr(double
a,double
b,double
eps)
  {
  return
asr(a,b,eps,simpson(a,b));
  }
  int
main()
  {
  scanf("%lf",&s);
  printf("%lf\n",asr(0,1e2,1e-10));
  return
0;
  }
  
  
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网