递归实现N!
递归实现:
C语言
#include<stdio.h>
int jiecheng(int);
int main()
{
int n=0;
printf("请输入一个正整数:\n");
scanf("%d",&n);
printf("阶乘结果是:%d\n",jiecheng(n));
return 0;
}
int jiecheng(int n)
{
if(n<=1)
{
return 1;
}else
{
return n*jiecheng(n-1);
}
}
C++语言:
递归:
#include<stdio.h>
long fac(int n) {
if(n>1)
{
return(n*fac(n-1));
}
else
return 1;
}
main() {
printf("10!=%ld\n",fac(10));
}
Java语言:
int result = 1;
public int nFactorial(int n) {
if (n > 0) {
result = result * n;
nFactorial(n - 1);
}
return result;
}
C#语言:
private static int CalJieCheng(int n)
{
if (n < 0)
{
throw new Exception("请示输入正整数!");
}
if (n < 2)
{
return 1;
}
else if (n > 16)
{
string text = string.Format("结果超出int32的范围:{0},无法显示!",int.MaxValue.ToString());
throw new Exception(text);
}
else
{
return n * Run(n - 1);
}
}
private static int Run(int m)
{
if (m == 1)
{
return 1;
}
return m * Run(m - 1);
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入正整数:");
string s = Console.ReadLine();
int n = int.Parse(s);
int reslut = CalJieCheng(n);
Console.WriteLine(s + "的阶乘是:" + reslut.ToString());
}
}
非递归C++语言:
非递归:
#include <iostream>
using namespace std;
int main(){
int fac=1;
for (int i=1;i<n;i++)
fac*=i;
cout << fac << endl;
return 0;
}