简体   繁体   中英

BigInteger FormatException

In my program, I get a FormatException with the message The value could not be parsed on the following line:

c = BigInteger.Parse("" + Math.Pow(b, 3));

The exception occurs when b = 99000, but if I manually replace b with 99000, the exception doesn't occur. I have also tested it with b = 99001, and other higher values but I don't get the error.

The underlying cause is that Math.Pow operates on doubles, not integral data types. By default, Double.ToString() returns only 15 digits of precision, and the double data type can only store a maximum of 17 digits of precision internally.

When b=100,000, b 3 = 1,000,000,000,000,000 (16 digits), and the conversion to a string will return the result as 1E+15 . BigInteger.Parse can only parse integral values (optional whitespace, followed by a sign, followed by 1 or more numbers), and will throw a FormatException when the string value "1E+15" is provided as an argument.

A solution is to avoid Math.Pow entirely, and to instead use BigInteger.Pow(BigInteger, int) . This approach avoids conversions to double entirely, and can exponentiate arbitrarily large integers.

With this change, your code might resemble something like this:

BigInteger c;
for (BigInteger b = 1; b < 1000000; b++)
{
   c = BigInteger.Pow(b, 3);
   // c stores b^3 as a BigInteger
}

Weird ... This seems to work for me, and you were right about the string in parse.

BigInteger c;
long b = 9000;
c = BigInteger.Parse("" + Math.Pow(b, 3));

No errors thrown ...

As for codemonkeh comment about the ToString() , you could also do this

BigInteger d = new BigInteger(Math.Pow(b, 3));

Assuming you are not running in a loop that will create heaps of those ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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