下面的代码将不停的计算你输入的整数的阶乘,直到输入一个非负数,结束程序。
#include <stdio.h>
int fact(int n);
int main(void) {
int current;
printf("Enter a positive integer [to terminate enter non-positive] > ");
scanf("%d", ¤t);
while (current > 0) {
printf("The factorial of %d is %d\n", current, fact(current));
printf("Enter a positive integer [to terminate enter non-positive] > ");
scanf("%d", ¤t);
}
}
// 如果 n 是一个正整数,fact() 将返回 n 的阶乘
int fact(int n) {
int lcv; // 循环控制变量
int p;
for(p=1, lcv=2; lcv <= n; p=p*lcv, lcv++);
return p;
}
可能的输出结果:
Enter a positive integer [to terminate enter non-positive] > 3
The factorial of 3 is 6
Enter a positive integer [to terminate enter non-positive] > 6
The factorial of 6 is 720
Enter a positive integer [to terminate enter non-positive] > 10
The factorial of 10 is 3628800
Enter a positive integer [to terminate enter non-positive] > 4
The factorial of 4 is 24
Enter a positive integer [to terminate enter non-positive] > 0