PAT基础编程题目集——6-8 简单阶乘计算

版权声明:余生请多指教,欢迎交流学习: https://blog.csdn.net/LYS20121202/article/details/83036508

原题目:

本题要求实现一个计算非负整数阶乘的简单函数。

函数接口定义:

int Factorial( const int N );

其中N是用户传入的参数,其值不超过12。如果N是非负整数,则该函数必须返回N的阶乘,否则返回0。

裁判测试程序样例:

#include <stdio.h>

int Factorial( const int N );

int main()
{
    int N, NF;
	
    scanf("%d", &N);
    NF = Factorial(N);
    if (NF)  printf("%d! = %d\n", N, NF);
    else printf("Invalid input\n");

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

5

输出样例:

5! = 120

分析:

1.题目保证输入值不会超过12,所以不用担心使用int时溢出,故直接走程序。

2.题目要求数值不会超过12,所以有可能小于0,对于小于0的值直接返回0,其他值则计算阶乘。

代码:

int Factorial( const int N )
{
  int i=1,a=1;
  if(N<0) return 0;
  else
  {
    for(i=1;i<=N;i++)
    {
      a=a*i;
    }
    return a;
  }
}

猜你喜欢

转载自blog.csdn.net/LYS20121202/article/details/83036508