简体   繁体   中英

Can't convert string to int: 'System.FormatException'

I'm having trouble converting a string to a integer, my program is failing on this line

int newS = int.Parse(s);

With message:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

The number I'm expecting back from my program is rather large. Below is the total program:

int math = (int)Math.Pow(2,1000);
string mathString = math.ToString();

List<string> list = new List<string>();

char[] ch = mathString.ToCharArray();
int result = 0;

foreach (char c in mathString)
{
    string newC = c.ToString();
    list.Add(newC);
    //Console.WriteLine(newC);
}

foreach (string s in list)
{
    int newS = int.Parse(s);
    result += newS;

}

Console.Write(result);
Console.ReadLine();

You answered your own question. An int can only store numbers up to 2147483648 and an unsigned int up to 4294967296. try to use an ulong instead. I'm not sure about this but maybe a signed long may work.

EDIT: actually, in the msdn page it says this:

If the value represented by an integer literal exceeds the range of ulong, a compilation error will occur.

So probably you need a double.

Math.Pow(2, 1000) returns -2147483648 .

So you'll end up with 11 items in your list, the first one being "-".

You can't convert a minus sign to int.

In all of the types of all languages are a limit on the numbers that you can save. The int of c# is -2,147,483,648 to 2,147,483,647. https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx

Math.Pow returns a double, when you want to cast it to int your variable gets the value 0

Math.Pow(2,1000) returns: 1.07150860718627E+301.

If you use the double format you will try to cast the . and the E and the +, that are not a int then you can't use a int to save it.

that returns the FormatException that are answered here: int.Parse, Input string was not in a correct format

Maybe you can try this:

int newS;

if (!int.TryParse(Textbox1.Text, out newS)) newS= 0;

result +=newS;

But will not use the 301 digits of the solution of 2^1000.

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