c语言输出各个数字的阶乘
时间: 2024-03-20 21:18:51 浏览: 16
以下是一个输出1到10的数字阶乘的C语言代码示例:
```
#include <stdio.h>
int main() {
int i, n, fact;
for (i = 1; i <= 10; i++) {
n = i;
fact = 1;
while (n > 0) {
fact *= n;
n--;
}
printf("%d! = %d\n", i, fact);
}
return 0;
}
```
输出结果:
```
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
```
该程序使用了for循环来遍历1到10的数字,然后使用while循环来计算每个数字的阶乘。在while循环中,我们将n从该数字开始递减,直到n等于1。在每个迭代中,我们将fact乘以n,从而计算出该数字的阶乘。最后,我们使用printf函数输出每个数字的阶乘。
相关问题
C语言代码输出5的阶乘
以下是C语言中输出5的阶乘的代码:
```c
#include <stdio.h>
int main() {
int num = 5;
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
printf("5的阶乘为:%d", factorial);
return 0;
}
```
输出结果为:
```
5的阶乘为:120
```
c语言用函数实现阶乘
以下是两种C语言用函数实现阶乘的例子:
1. 使用递归函数实现阶乘
```c
#include <stdio.h>
long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
int main() {
int n;
printf("Input n:");
scanf("%d", &n);
printf("%d!=%ld\n", n, factorial(n));
return 0;
}
```
2. 使用循环函数实现阶乘
```c
#include <stdio.h>
long factorial(int n) {
long pro = 1;
for (int i = 1; i <= n; i++) {
pro *= i;
}
return pro;
}
int main() {
int n;
printf("Input n:");
scanf("%d", &n);
printf("%d!=%ld\n", n, factorial(n));
return 0;
}
```