lzth.net
当前位置:首页 >> C语言如何用递归算法求1!+2!+3!+...n! >>

C语言如何用递归算法求1!+2!+3!+...n!

#include<stdio.h> float fun(int n) { if(n==1) return 1;//如果n=1则直接返回1 return n*fun(n-1);//否则返回n*fun(n-1),以此计算n的阶乘,这条语句就是递归体 } void main() { int i; float sum=0; for(i=1;i<=n;i++){ sum+=fun(i); //循环调用,用sum累计 } printf("sum=%.2f\n",sum); }

# include <stdio.h>int fun5(int n){if(n==0)return 0; return n+fun5(n-1);}int main(){int n; scanf("%d",&n); printf("%d\n",fun5(n)); return 0;}

#include "stdio.h" int sum1ton(int n) { if(n == 1): return 1; else return n + sum1ton(n - 1); } void main() { int n; scanf("%d",&n); int s = sum1ton(n); printf("%d",s); }

#includelong fun(int n)//递归单个阶乘 { if(n == 1) return 1; else return fun(n - 1) * n;}int main(){ int n, i; long num = 0; scanf("%d", &n); for(i = n; i > 0; i--)//累加阶乘 num += fun(i); printf("%ld\n", num);}

#include"math.h" int fun(int n) { int s=0; if(1==n) return(1); if(n!=0) {s+=fun(--n)+n ; return s+1 ;} } main() { int n,i,j=1; printf("\ninpt n:"); scanf("%d",&n); i=n; while(i--) { if(i==n-1) printf("%d",j++); else printf("+%d",j++); } printf("\n=%d",fun(n)); } 输出 1+2+3++n =fun(n) 测试的 你自己看看好不好咯.

#include int fun(int n){ if(n==1)return 1; else return fun(n-1)+n; } int main(){ int n; printf("请输入n的值:"); scanf("%d",&n); printf("%d\n",fun(n)); return 0; }

你好!#include int Sum(int n) { int sum = 0; if(n == 0) return 0; return n + Sum(n - 1);}int main() { printf("%d\n",Sum(100)); return 0;}如有疑问,请追问.

int N(int x) { if(x==0) { return 1; }else{ return x*N(x-1) } } int iRet=0; for(int i=1;i<=n;i++) { iRet += N(i); }

void main() { printf("f(n)=%d\n",f(n)); } int f(int n) { if(n>0) return n*n+f(n-1); return 0; }

int foo(int n){ if(n==1) return 1; else { return f(n-1)+n; } }

网站首页 | 网站地图
All rights reserved Powered by www.lzth.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com