c语言计算n的阶乘

c语言计算n的阶乘的方法有:一、循环方法;二、递归方法。循环方法有:1、while语句循环实现;2、for语句实现。while是计算机的一种基本循环模式。 当满足条件时进入循环,进入循环后,当条件不满足时,跳出循环。

一、循环方法

1、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;
}

结果:

5
120

2、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
120

二、递归方法

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;
}

结果:

5
120

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;
}

结果:

5
120

延伸阅读

什么是阶乘

阶乘是基斯顿·卡曼(Christian Kramp,1760~1826)于 1808 年发明的运算符号,是数学术语。一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。1808年,基斯顿·卡曼引进这个表示法。亦即n!=1×2×3×…×(n-1)×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。

文章标题:c语言计算n的阶乘,发布者:Z, ZLW,转载请注明出处:https://worktile.com/kb/p/47196

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Z, ZLW的头像Z, ZLW

发表回复

登录后才能评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部