c - 对于较大的输入值(例如 50),程序不返回输出。它返回 0。这是一个使用递归的阶乘程序

标签 c

/*Program to find factorial of a number using recursion*/ 

#include<stdio.h>
#include<stdlib.h>
/*Function to recursively compute factorial of a number*/
long int fact(long int n)
{
    if(n==0)
    return 1;
    return n*fact(n-1);
}
int main()
{
    long  int n;
    printf(" enter n ");
    scanf("%ld",&n);
    printf ("%ld",fact(n));  
    return 0;
}

最佳答案

50!30414093201713378043612608166064768844377641568960512000000000000 或大约 3.04e+64,一个 215 位数字。此值通常超出类型的范围,例如 long。甚至 uintmax_tunsigned long long 也只需要能够表示至少 64 位整数。

long int fact(long int n) {
  ...
  // Overflows!
  return n*fact(n-1);

要获得准确的答案,代码可以使用替代类型。以下使用整数的字符串/十进制表示。它适用于较大的 n 值,因为正确的功能受到缓冲区大小的限制。

char *strfact_mult(char *s, unsigned x) {
  unsigned sum = 0;
  size_t len = strlen(s);
  size_t i = len;
  while (i > 0) {
    sum += (s[--i] - '0')*x;
    s[i] = sum%10 + '0';
    sum /= 10;
  }
  while (sum) {
    len++;
    memmove(&s[1], s, len);
    s[i] = sum%10 + '0';
    sum /= 10;
  }
  return s;
}

char *str_fact(char *dest, unsigned n) {
  strcpy(dest, "1");
  while (n > 1) {
    strfact_mult(dest, n--);
  }
  return dest;
}

int main(void) {
  char buf[1000];
  puts(str_fact(buf, 0));
  puts(str_fact(buf, 1));
  puts(str_fact(buf, 5));
  puts(str_fact(buf, 50));
}

输出

1
1
120
30414093201713378043612608166064768844377641568960512000000000000

关于c - 对于较大的输入值(例如 50),程序不返回输出。它返回 0。这是一个使用递归的阶乘程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397514/

相关文章:

c - 链表中队列的实现

有人可以帮助解释这个 fft 代码片段中发生了什么

C程序错误:checking if password is valid

c - DB2 存储过程在 C 程序中返回游标的多行

C 类型定义 : pointer to struct

c - MPI_Scatter 动态二维数组行导致段错误

c - 堆栈结构如何与函数内的复合语句一起使用?

c - 使用指针在 C 中复制多维数组时出现段错误

C - 用户输入被跳过?

C 编译器在表达式中的前/后增量求值