如何实现在C ++中的阶乘函数? [英] How do you implement the factorial function in C++?

查看:305
本文介绍了如何实现在C ++中的阶乘函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:
  计算阶乘大C ++中
   HOWTO计算x

Possible Duplicates:
Calculating large factorials in C++
Howto compute the factorial of x

如何实现在C ++中的阶乘函数?而我的意思是使用任何参数检查和错误处理逻辑适用于在C ++中通用的数学库正确实施。

How do you implement the factorial function in C++? And by this I mean properly implement it using whatever argument checking and error handling logic is appropriate for a general purpose math library in C++.

推荐答案

递归:

unsigned int factorial(unsigned int n) 
{
    if (n == 0)
       return 1;
    return n * factorial(n - 1);
}

迭代:

unsigned int iter_factorial(unsigned int n)
{
    unsigned int ret = 1;
    for(unsigned int i = 1; i <= n; ++i)
        ret *= i;
    return ret;
}

编译时间:

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

这篇关于如何实现在C ++中的阶乘函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆