C 语言函数求阶乘251
阶乘,通常表示为 n!,是将正整数 n 从 1 乘到 n 的结果。例如,5! = 5 × 4 × 3 × 2 × 1 = 120。
在 C 语言中,我们可以编写一个函数来计算给定整数的阶乘:```c
#include
int factorial(int n) {
int result = 1;
while (n > 1) {
result *= n;
n--;
}
return result;
}
int main() {
int num;
printf("输入一个整数: ");
scanf("%d", &num);
printf("%d 的阶乘: %d", num, factorial(num));
return 0;
}
```
以下是函数的工作原理:
它接受一个正整数 n 作为参数。
它将 result 初始化为 1,这是阶乘的初始值。
它使用 while 循环,只要 n 大于 1 就执行循环。
在循环中,它将 n 乘以 result 并将 n 减 1。
一旦 n 等于 1,循环就会退出,此时 result 将包含阶乘值。
最后,函数返回 result。
在 main() 函数中:
它从用户获取一个整数。
它调用 factorial() 函数来计算该整数的阶乘。
它打印出阶乘值。
这个程序的输出如下,假设用户输入 5:```
输入一个整数: 5
5 的阶乘: 120
```
请注意,此算法的时间复杂度为 O(n),其中 n 是要计算阶乘的整数。对于大型 n 值,可能需要优化或使用其他算法。
2024-11-14
上一篇:C 语言中输出多个星号的多种方法
下一篇:C 语言中的函数
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html