I want to square every digit in str
and concatenate it to pow
.
I have this simple code:
string str = "1234";
string pow = "";
foreach(char c in str)
{
pow += Math.Pow(Convert.ToInt32(c), 2);
}
It should return 14916
- instead it returns: 2401250026012704
But if I use int.Parse(c)
, it returns the correct number.
foreach(char c in str)
{
int i = int.Parse(c.ToString());
pow += Math.Pow(i, 2);
}
Why does Parse
work and Convert
doesn't?
Math.Pow(Char.GetNumericValue(c), 2)
. You should not compare apples with pears. Once you convert achar
toint
and then you parse aString
toint
. The rules are different.