c语言如何计算n的阶乘

本篇内容主要讲解“c语言如何计算n的阶乘”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“c语言如何计算n的阶乘”吧!

10年建站经验, 做网站、成都网站建设客户的见证与正确选择。创新互联建站提供完善的营销型网页建站明细报价表。后期开发更加便捷高效,我们致力于追求更美、更快、更规范。

c语言计算n的阶乘的方法:1、通过for循环计算阶乘,代码如“for (i = 1; i <= n; i++){fact *= i;}”;2、通过while循环计算阶乘,代码如“while (i <= fact="" int="" res="n;if" n=""> 1)res...”。

一、问题

Problem Description

给定一个整数n,求它的阶乘,0≤n≤12

Input

输入一个数n

Output

输出一个数,表示n的阶乘

Sample Input

5

Sample Output

120

二、分析

既然是求阶乘的,那突破点就很明显,

突破点就在阶乘

阶乘的概念及背景

1️⃣概念:

一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。

2️⃣背景:

1808年,基斯顿·卡曼(Christian Kramp,1760~1826)引进这个表示法。

3️⃣阶乘的计算方法:

任何大于等于1 的自然数n 阶乘表示方法:

n!=1×2×3×…×(n-1)×n 或 n!=n×(n-1)!

注意:0的阶乘为1,即 0!=1。
1! = 1
2! = 2 * 1 = 2
3! = 3 * 2 * 1 = 6

n! = n * (n-1) *… * 2 * 1

在了解这些之后,可以开始先尝试用代码进行实现一下,然后再看下面代码做一次检查。

三、求解

关于C语言实现n的阶乘,目前入门阶段,我们主要有以下两种写法:

第一种:循环

①for循环

#include<stdio.h>int main(){
int n;
scanf("%d", &n);
int fact = 1;
int i;
for (i = 1; i <= n; i++)
{
fact *= i;
}
printf("%d\n", fact);
return 0;}

测试样例:5

1 * 2 * 3 * 4 * 5 = 120

5120--------------------------------Process exited after 1.475 seconds with return value 0请按任意键继续. . .

②while循环

#include<stdio.h>int main(){
int n;
scanf("%d", &n);
int fact = 1;
int i = 1;
while (i <= n)
{
fact *= i;
i++;
}
printf("%d\n", fact);
return 0;}

测试样例:6

1 * 2 * 3 * 4 * 5 * 6 = 720

6720--------------------------------Process exited after 1.549 seconds with return value 0请按任意键继续. . .
第二种:递归(函数调用自身)

1️⃣写法一

#include <stdio.h>int Fact(int n);int main() //主函数{
   int n, cnt;
   scanf("%d", &n);
   cnt = Fact(n);
   printf("%d\n", cnt);
   return 0;}
   int Fact(int n)    //递归函数
   {
   int res = n;
   if (n > 1)
       res = res * Fact(n - 1);
   return res;}

测试样例:7

7 * 6 * 5 * 4 * 3 * 2 * 1
= 1 * 2 * 3 * 4 * 5 * 6 * 7
= 5040

75040--------------------------------Process exited after 2.563 seconds with return value 0请按任意键继续. . .

当然也可以写成这样:

2️⃣写法二

#include <stdio.h>int Fact(int n) //递归函数 {
   int res = n;
   if (n > 1)
       res = res * Fact(n - 1);
   return res;}int main() //主函数 {
   int n, cnt;
   scanf("%d", &n);
   cnt = Fact(n);
   printf("%d\n", cnt);
   return 0;}

测试样例:6

6 * 5 * 4 * 3 * 2 * 1
= 1 * 2 * 3 * 4 * 5 * 6
= 720

6720--------------------------------Process exited after 1.829 seconds with return value 0请按任意键继续. . .

到此,相信大家对“c语言如何计算n的阶乘”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

网站名称:c语言如何计算n的阶乘
新闻来源:https://www.cdcxhl.com/article24/igghce.html

成都网站建设公司_创新互联,为您提供全网营销推广品牌网站制作外贸建站企业建站营销型网站建设网站策划

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都seo排名网站优化