繁体   English   中英

为什么是阶乘 13! 对 unsigned long long int 不起作用?

[英]why the factorial 13! doesn't work with unsigned long long int?

我正在做作业,我需要做一个程序。我需要做一个 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;
}

你必须

  • 使用unsigned long long而不是int
  • 从函数return值而不是写入其参数
  • printf使用%llu格式说明符而不是%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! 或更大。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM