首页 > 其他 > 详细

12 计算阶乘, for 和 递归

时间:2020-05-27 15:52:59      阅读:53      评论:0      收藏:0      [点我收藏+]
// for循环计算阶乘
#include    <stdio.h>

int get_input(void);
int fac(int);

main()
{
int input;
int ans;
printf("This progame calculates factorial.\n");
printf("Please Input a number :\n");
input = get_input();
ans = fac(input);
if (ans=-1)
printf("Calculate the factorial of %d ? Are you sure?\n", input);
else
printf("The factorial of %d is %d\n", input, ans);
}

int get_input(void)
{
int input;
char ch;

while (scanf_s("%d", &input) != 1)
{
while ((ch = getchar()) != \n)
putchar(ch);

printf(" is Not a number\n");
printf("Input again:");
}
return input;
}

int fac(int n) {
int res = 1;
int i;

if (n <= 0)
res = -1;

for (i = 1;i <= n;i++)
res *= i;

return res;
}

 

12 计算阶乘, for 和 递归

原文:https://www.cnblogs.com/abel2020/p/12973288.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!