0

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();
DavidG
  • 113,891
  • 12
  • 217
  • 223
johnnewbie25
  • 149
  • 4
  • 12
  • Have you looked to see what mathString is? If that's 2^1000 that's larger than a 32 but int can handle I'm pretty sure so I'm not sure what type casting would do, but probably not what you want. – bkribbs Jun 10 '15 at 23:39
  • Should not you be using `BigInteger`? – Alexei Levenkov Jun 10 '15 at 23:46

3 Answers3

0

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.

0

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.

0

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.

Community
  • 1
  • 1
BrunoLoops
  • 554
  • 5
  • 20