c - c中返回表达式的用途

标签 c function return-type

#include<stdio.h>

long int multiplyNumbers(int n);

int main() 
{
    int n;

    printf("Enter a positive integer: ");
    scanf("%d",&n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));

    return 0;
}

long int multiplyNumbers(int n)
{
    if (n>=1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}

上述程序中return n*multiplyNumbers(n-1);的用途是什么?它到底有什么作用?

最佳答案

好吧,代码n * multiplyNumbers(n-1)是一个递归调用,记住数字的阶乘是n! = n*(n-1)* (n-2) * ... *(n-(n-1)),n *MultiplyNumbers(n-1) 遵循以下定义阶乘。

我推荐阅读 https://en.wikipedia.org/wiki/Recursion https://en.wikipedia.org/wiki/Factorial 为了更好地理解为什么我们使用这个递归代码。

关于c - c中返回表达式的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75762776/

相关文章:

javascript - 在 javascript 函数中返回不同类型也是错误的吗?

c++ - Windows 上有用的开源库/项目

c++ - c 是否优化了 for 循环的检查部分?

c - strncat() 再次复制到同一个字符串

javascript - 如何 return 或 console.log 我的函数以返回我选择的数组?

java - 如何在项目中搜索返回 Collection 接口(interface)实现的所有方法?

c - 强制 doxygen 模块以小写字母开头

setInterval 中的 Javascript 函数

javascript - 在 javascript 中使用交通灯序列函数时,图像不显示

c# - 从函数返回多个列表