原
#include <stdio.h>
int main(){
int n;
int sum = 1;
printf("输入数字:");
scanf("%d", &n);
for (int i = 1;i <= n ;i++ ) {
sum *= i;
}
printf("%d的阶乘为%d\n", n, sum);
return 0;
}
优化
#include <stdio.h>
int main() {
int num;
int factorial = 1;
printf("输入数字:");
scanf("%d", &num);
if (num <= 0) {
printf("无效输入!请输入一个正整数。\n");
return 1;
}
for (int i = 1; i <= num; i++) {
factorial *= i;
}
printf("%d的阶乘为%d\n", num, factorial);
return 0;
}
递归
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num;
printf("输入数字:");
scanf("%d", &num);
if (num < 0) {
printf("无效输入!请输入一个非负整数。\n");
return 1;
}
int result = factorial(num);
printf("%d的阶乘为%d\n", num, result);
return 0;
}
标签:return,int,C语言,factorial,num,printf,阶乘
From: https://www.cnblogs.com/code3/p/17500902.html