C 语言实例 - 阶乘

C 语言教程 · 2019-02-20 19:26:48

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

n!=1×2×3×...×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n

实例

#include <stdio.h> int main() { int n, i; unsigned long long factorial = 1; printf("输入一个整数: "); scanf("%d",&n); // 如果输入是负数,显示错误 if (n < 0) printf("Error! 负数没有阶乘jiechen"); else { for(i=1; i<=n; ++i) { factorial *= i; // factorial = factorial*i; } printf("%d! = %llu", n, factorial); } return 0; }

运行结果:

输入一个整数: 10
10! = 3628800

实例 - 使用递归

#include <stdio.h> long int multiplyNumbers(int n); int main() { int n; printf("输入一个整数: "); scanf("%d", &n); printf("%d! = %ld", n, multiplyNumbers(n)); return 0; } long int multiplyNumbers(int n) { if (n >= 1) return n*multiplyNumbers(n-1); else return 1; }

点击查看所有 C 语言教程 文章: https://codercto.com/courses/l/17.html

查看所有标签

Learning Processing

Learning Processing

Daniel Shiffman / Morgan Kaufmann / 2008-08-15 / USD 49.95

Book Description Teaches graphic artists the fundamentals of computer programming within a visual playground! Product Description This book introduces programming concepts in the context of c......一起来看看 《Learning Processing》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具