为什么阶乘13!与unsigned long long int不兼容?

时间:2019-04-22 15:39:54

标签: c

我正在做作业,我需要做一个程序。我需要做n> 12的阶乘,但我却做了所有事情,但我没有解决办法。

出现我的问题是因为我使用unsigned long long并且它只有32个字节。但是13!比这个多。 我需要使用long double,但是我不知道如何使用它。

#include <stdio.h>
#include <stdlib.h>
unsigned long long factorial(int x) 
(13!>2^32-1)--> max 32 bytes
   {int i=1;
    int aux=1;
    int p;
    p= x+1;
        while (i<p)
        {
        aux*=i;
        i++;
        }
     x=aux;
   };
int main()
{
    float v1=0;
    int e1=0;
    while(e1<1 || e1>12)
        {printf("Ingrese un valor: ");
        scanf("%f",&v1);
        e1=v1/1;/
        if(e1!=v1)
            printf("Solo se considera el numero entero: %d \n",e1);
        if(e1>12)
            printf("Este programa solo calcula hasta 12! (12 factorial) \n\n");}
    printf("El factorial de %d es: %d \n",e1,factorial(e1));
    printf("%d! = %d \n",e1,factorial(e1)); 
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您必须

  • 使用unsigned long long而不是int
  • return来自函数的值,而不是写入其参数
  • 使用%llu中的printf格式说明符代替%d

赞:

#include <stdio.h>

unsigned long long factorial(int x)
{
    unsigned long long aux = 1;
    while(x > 1) {
        aux *= x;
        x--;
    }
    return aux;
}

int main(void)
{
    for(int i = 0; i <= 20; i++) {
        printf("%d! = %llu\n", i, factorial(i));
    }
    return 0;
}

程序输出:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000

但是64位整数不能处理21!或更高。

相关问题