首页 > 后端开发 > C++ > 正文

C程序中的阶乘程序

王林
发布: 2023-09-09 11:17:02
转载
1283人浏览过

c程序中的阶乘程序

Given with the number n the task is to calculate the factorial of a number. Factorial of a number is calculated by multiplying the number with its smallest or equal integer values.

Factorial is calculated as −

0! = 1
1! = 1
2! = 2X1 = 2
3! = 3X2X1 = 6
4! = 4X3X2X1= 24
5! = 5X4X3X2X1 = 120
.
.
.
N! = n * (n-1) * (n-2) * . . . . . . . . . .*1
登录后复制

Example

的中文翻译为:

示例

Input 1 -: n=5
   Output : 120
Input 2 -: n=6
   Output : 720
登录后复制

There are multiple methods that can be used −

豆包AI编程
豆包AI编程

豆包推出的AI编程助手

豆包AI编程 483
查看详情 豆包AI编程
  • Through the loops
  • Through recursion which is not at all effective
  •  Through a function

Given below is the implementation using functions

Algorithm

Start
Step 1 -> Declare function to calculate factorial
   int factorial(int n)
      IF n = 0
         return 1
      End
      return n * factorial(n - 1)
step 2 -> In main()
   Declare variable as int num = 10
   Print factorial(num))
Stop
登录后复制

使用C语言

例子

#include<stdio.h>
// function to find factorial
int factorial(int n){
   if (n == 0)
   return 1;
   return n * factorial(n - 1);
}
int main(){
   int num = 10;
   printf("Factorial of %d is %d", num, factorial(num));
   return 0;
}
登录后复制

输出

Factorial of 10 is 3628800
登录后复制

使用C++

示例

#include<iostream>
using namespace std;
// function to find factorial
int factorial(int n){
   if (n == 0)
   return 1;
   return n * factorial(n - 1);
}
   int main(){
   int num = 7;
   cout << "Factorial of " << num << " is " << factorial(num) << endl;
   return 0;
}
登录后复制

输出

Factorial of 7 is 5040
登录后复制

以上就是C程序中的阶乘程序的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号