我的代码对数字进行阶乘,但由于某种原因,每当我输入 13 或更高的数字时,它要么给出错误的数字,要么以某种方式得到负数。有什么建议么?
List<int> myList = new List<int>();
Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
string A = Console.ReadLine();
int C = Convert.ToInt32(A);
int k = C;
int B = C;
int U = C - 1;
Console.Write("{0} ", B);
while (U != 0)
{
k *= U;
Console.Write("* {0} ", U);
U--;
}
Console.WriteLine(" = {0}", k);
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
整数为 32 位,因此最大值为 2,147,483,647。13!等于更大的值:6,227,020,800。您必须将 更改为long
大于 12!,作为 64 位数字,最多可达 9,223,372,036,854,775,807。
Type Max Fact Max Value
int 12! 6,227,020,800
long 20! 9,223,372,036,854,775,807
ulong 20! 18,446,744,073,709,551,615
Run Code Online (Sandbox Code Playgroud)
改为 long 至少可以让你达到 20!您必须更改为浮点才能超出大多数系统中的浮点数,即使如此,您也会开始看到舍入错误。即使是无符号长整型也无法达到 21!
现在,要超过 20!,您可以使用 BigInteger 结构(这里有很棒的代码项目示例)。它没有定义的上限或下限,但如果数字对于您的系统来说太大,您可能会遇到内存/系统问题。根据 MSDN:
BigInteger 类型是一种不可变类型,表示任意大的整数,其值理论上没有上限或下限。
int factorial = 25;
BigInteger bigInt = 1;
while (factorial > 1)
bigInt = BigInteger.Multiply(factorial--, bigInt);
var output = bigInt.ToString(); // Would give you the 26 digits
Run Code Online (Sandbox Code Playgroud)
资源: