卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64336本站已运行4115

c语言怎么求阶乘

计算 c 语言中求整数阶乘有递归、循环和迭代 3 种方法,对于较小 n 值(n

c语言怎么求阶乘

C 语言中计算阶乘

在 C 语言中,求一个整数的阶乘有以下几种方法:

1. 递归方法

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

2. 循环方法

int factorial(int n) {
    int result = 1;
    for (int i = 1; i <p><strong>3. 迭代方法</strong></p><pre class="brush:php;toolbar:false">int factorial(int n) {
    int result = 1;
    while (n &gt; 0) {
        result *= n;
        n--;
    }
    return result;
}

哪种方法更好?

对于较小的 n 值(例如 n

示例

计算 5 的阶乘:

int result = factorial(5);
printf("5 的阶乘是 %dn", result);

输出:

5 的阶乘是 120
卓越飞翔博客
上一篇: c语言中的continue怎么用
下一篇: 深入了解golang框架
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏