ntjm.net
当前位置:首页 >> C语言编程:用递归与非递归求n! >>

C语言编程:用递归与非递归求n!

由于长整型数据有限制 这个阶层算不了多大的 测试的时候就用一位数吧如果不能用再追问我吧①递归#include "stdio.h"#include "conio.h"main(){ int input; long result; long f(int n); scanf("%d",&input); result = f(input); printf("%d! = %ld",

非递归:#include void main(){ int i,t=0; for (i=1;iint suan(int n){ if(n==1){ return n; } return n+suan(n-1);} void main(){ int n=1; suan(n);}

#include <stdio.h>//递归求n! int func1(int n){ if(n==1) return 1; else return func1(n-1)*n;}//递归求Fibonacci int func2(int n){ if(n==1 || n==2) return 1; else return func2(n-1)+func2(n-2);}//非递归求n! int func3(int n){ int i,sum=1; for(i=1;i<=n;i++) {

int fac(int n) //非递归 {int f=1; for(;n;)f*=n--; return f; } int fac1(int n) //递归 {if(n==0)return 1; return n*fac1(n-1); }

#include <stdio.h>int rf(int n){ return n > 0 ? n * rf(n-1) : 1;}int f(int n){ int k = 1; while(n > 0) k *= n--; return k;}int main(){ int n; scanf("%d", &n); printf("递归:%d\n", rf(n));printf("非递归:%d\n", f(n));}

//递归.#include<stdio.h>int main(){int fun(int a);int n=10;n=fun(n);printf("n!=%d\n",n);return 0;}int fun(int a){if(a==1)return a;if(a>0)return a*fun(a-1);}

算递归最好用double类型,否则很容易溢出.#include<stdio.h>double fact(double x){ if(x==0) return 1; else return fact(x-1) * x;}int main(){ int x; scanf("%d", &x); printf("%f", fact(x)); return 0;}

#includelong con(int a){ int i; long add=1; for(i=1;i>n>>r;//输入时用空格隔开 cout cout}

刚意识到递归和循环两回事,献丑了#include <stdio.h> int main(){ printf("设定n的值:"); long long n,factorial=1,count; scanf("%lld",&n); for(count=1;count<=n;count++) { factorial*=count; } printf("factorial=%lld\n",factorial); return 0; }

//递归 long Recursion(int n) { return n <= 1 ? 1 : n * Recursion(n - 1); }//非递归 long NoRecursion(int n) { long r = 1; for (int i = n; i > 0; i--) r *= i; return r; }

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