我用阶乘(使用递归)计算的代码最多可以达到24,但在c中显示了错误的答案.请检查


#include <stdio.h>
int main()
{
int n, t, rem, i, j, k;
scanf("%d", &t);
int ans[t], integer[1000];
for(i=0; i<t; i++)
{
int count=0;
scanf("%d", &n);
for(j=0; j<1000; j++)
{
integer[j]=0;
}
for(j=0, k=n; k>0; k/=10, j++)
{
integer[j]=k%10;
count++;
}
factorial(n, count, integer);
}
return 0;
}
void factorial(int n, int count, int* integer)
{
int i, j, k, rem=0, temp;
if(n==1)
{
for(i=count-1; i>=0; i--)
{
printf("%d", integer[i]);
}
printf("n");
return;
}
else
{
for(i=0; i<count; i++)
{
temp=integer[i]*(n-1);
integer[i]=(temp%10)+rem;
rem=temp/10;
if(i==count-1)
{
if(rem!=0)
{
for(j=0, k=rem; k>0; k/=10, j++)
{
integer[count]=k%10;
count++;
}
break;
}
}
}
factorial(n-1, count, integer);
}
}

说明:我以相反的方式保存数字ex输入:100整数保存在数组中:0 0 1 0 0 0。。。然后,当调用阶乘函数时,它将n=100,count=3和整数数组作为输入。我们将数组的第一个元素乘以n-1,并将余数。。。这种情况一直持续到整个整数数组乘以99,然后我们再次调用factorial,从而将数组乘以98,以此类推,直到我们达到1,最终打印出答案。

问题:代码只给出了24的正确结果,之后给出了错误的输出。

您假设整数中的每个元素都在0和9之间,但事实并非如此,在写入数字后添加一个空格表示问题,例如计算从1到22:的事实

1 
2 
6 
2 4 
1 2 0 
7 2 0 
5 0 4 0 
4 0 3 2 0 
3 6 2 8 8 0 
3 6 2 8 8 0 0 
3 9 9 1 6 8 0 0 
4 7 8 10 0 1 6 0 0 <<< wrong value for !12
6 2 2 7 0 2 0 8 0 0 
8 7 1 7 8 2 9 1 2 0 0 
1 3 0 7 6 7 4 3 6 8 0 0 0 
2 0 9 2 2 7 8 9 8 8 8 0 0 0 
3 5 5 6 8 7 4 2 8 0 9 6 0 0 0 
6 4 0 2 3 7 3 7 0 5 7 2 8 0 0 0 
1 2 1 6 4 5 0 10 0 4 0 8 8 3 2 0 0 0  <<< wrong value for 19
2 4 3 2 9 0 2 0 0 8 1 7 6 6 4 0 0 0 0 
5 1 0 9 0 9 4 2 1 7 1 7 0 9 4 4 0 0 0 0 
1 1 2 3 10 0 0 7 2 7 7 7 7 6 0 7 6 8 0 0 0 0 <<< wrong value for 22

所以你的问题来了,因为你没有管理足够的携带

4 78 100 1 6 0中的示例以正确的方式处理会产生预期的4 79 01 6 0

在行之后的阶乘中解决该问题

rem=temp/10;

添加

if (integer[i] > 9)
{
rem += integer[i] / 10;
integer[i] %= 10;
}

其中:

  • ans[t]是无用的
  • 使用scanf或等效函数时,请检查结果以确保输入了有效值
  • 如果结果使用了以10为基数的1000位以上的数字,您将写出整数

计算溢出了整数的能力。

相关内容

最新更新