Search code examples
c#mathcalculus

Calculate checksum in C#


numbers[i] = numbers[i] * 2;

if (numbers[i] >= 10)
{
   string t = numbers[i].ToString();
   Console.WriteLine(t[0] + " plus " + t[1]+" = "+quersumme(t).ToString());
   numbers[i] = Convert.ToInt32(t[0]) + Convert.ToInt32(t[1]);
}

public int quersumme(string n)
{
   return n[0] + n[1];
}

The function returns 101 when I enter 7. But 7 * 2 = 14 and quersumme should do 1+4 = 5


Solution

  • t[0] is the character '1', and t[1] is the character '4', which is translated to 49 + 52, hence 101. Check out an ASCII chart to see what I'm talking about.

    You could try using the Char.GetNumericValue() function:

    return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);