c语言pat基础题改错

img


#include <stdio.h>

void Print_Factorial ( const int N );

int main()
{
    int N;
    
    scanf("%d", &N);
    Print_Factorial(N);
    return 0;
}

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

我的答案如下:


void Print_Factorial ( const int N ){
    int sum=1;
    if(N>=0&&N<=1000){
        for(int i=1;i<=N;i++){
                sum*=i;
        }
        printf("%d\n",sum);
    }else{
        printf("Invalid input");
    }
}

img

修改如下,供参考:

/* 你的代码将被嵌在这里 */
void Print_Factorial(const int N) 
{
    if (N < 0 || N > 1000) 
        printf("Invalid input");
    else {
        int i, j;//定义循环变量 
        int temp;//定义中间结果变量 
        int carry;//定义进位数变量 
        int len = 1;//定义结果长度变量 
        int a[10000] = { 1 };//定义结果数组,a[0] = 1;
        for (i = 2; i <= N; i++)//循环N次,求N的阶乘 
        {
            carry = 0;//使每次进位数为零 
            for (j = 0; j < len; j++)//保存每一位数字并判断结果是否需要增长 
            {
                temp = a[j] * i + carry;//计算中间结果 
                a[j] = temp % 10;//保存每一位数字,从后往前 
                carry = temp / 10;//计算进位数  
                if (j >= len - 1 && carry > 0)//判断结果是否需要增长 
                    len++;
            }
        }
        for (i = len - 1; i >= 0; i--)//输出最终结果 
        {
            printf("%d", a[i]);
        }
    }
}

1000的阶乘你的Int是根本存不下的
只能用高精度

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^