gpt4 book ai didi

c - 我计算 99 以内数字的阶乘的代码中的错误在哪里?

转载 作者:行者123 更新时间:2023-11-30 19:11:45 24 4
gpt4 key购买 nike

我正在使用老式的乘法方法来计算阶乘,但对于大于 13 的数字,我仍然得到错误的答案。我知道没有数据类型可以准确地保存这么大的值,所以我使用一个数组来存储每个数字中单独的数字。

代码中的“cas”表示要计算阶乘的个数。

这是代码-

void factorial (int cas)
{
int num[158];
num[0] = 1;

for (int i=1; i<158; i++)
{
num[i] = 0;
}

int row1[158];
int row2[158];
int length = 0;
int max = 0;
int carry = 0;

for (int j=1; j<=cas; j++)
{
for (int i=0; i<158; i++)
{
row1[i] = 0;
row2[i] = 0;
}

for (length=157; length>=0; length--)
{
if (num[length] != 0)
break;
}

if (j/10 < 1)
{
int* ptr = num;
carry = 0;

for (int i=0; i<=length; i++)
{
int mult = (j * num[i]) + carry;
int units = mult % 10;
carry = mult / 10;
*ptr = units;
ptr++;
}
*ptr = carry;
}
else
{
int* ptr = num;
int* ptr1 = row1;
row2[0] = 0;
int* ptr2 = row2 + 1;
carry = 0;

for (int i=0; i<=length; i++)
{
int mult = ((j%10) * num[i]) + carry;
int units = mult % 10;
carry = mult / 10;
*ptr1 = units;
ptr1++;
}
*ptr1 = carry;

for (int i=0; i<=length; i++)
{
int mult = ((j/10) * num[i]) + carry;
int units = mult % 10;
carry = mult / 10;
*ptr2 = units;
ptr2++;
}
*ptr2 = carry;

for (max=157; max>=0; max--)
{
if (row1[max] != 0 || row2[max] != 0)
break;
}

carry = 0;

for (int i=0; i<=max; i++)
{
int add = row1[i] + row2[i] + carry;
int units = add % 10;
carry = add / 10;
*ptr = units;
ptr++;
}
*ptr = carry;
}

}
for (length=157; length>=0; length--)
{
if (num[length] != 0)
break;
}

for (;length>=0;length--)
{
printf("%i",num[length]);
}

printf("\n");
}

最佳答案

在乘以数字的十位部分之前,您忘记将进位重置为 0。

  }
*ptr1 = carry;

carry = 0; // ADDED LINE: Reset carry before multiplying with the tens part

for (int i=0; i<=length; i++)
{
int mult = ((j/10) * num[i]) + carry;

关于c - 我计算 99 以内数字的阶乘的代码中的错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39224407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com