0
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

Liam Schnell
  • 474
  • 8
  • 25

5 Answers5

8

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]);
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
5

You're currently summing the Unicode code points - '1' is 49, and '4' is 52, hence the 101. You want to take the digit value of each character.

If you know that the digits will be in the range '0'-'9', the simplest way of doing that is just to subtract '0' and to use the LINQ Sum method to sum each value:

public int SumDigits(string n)
{
   return n.Sum(c => c - '0');
}

Or you could use Char.GetNumericValue(), but that returns double because it also copes with characters such as U+00BD: ½.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @Jodrell: Well, sort of. You can definitely do it without. On the other hand, as it's about *digits*, you could argue it's about a textual representation of the number. – Jon Skeet Mar 19 '13 at 16:42
0

Try converting n[0] and n[1] to separate int32's in your quersomme function

Haden693
  • 174
  • 1
  • 8
0

You are doing string concatenation in quesumme method.

Should be:

public int quersumme(string n)
{
   return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);
}
Yahya
  • 3,386
  • 3
  • 22
  • 40
0

It looks to me like you are trying to enumerate the digits in an int.

Try this to avoid slow and cumbersome parsing and conversion. (Its all relative, I haven't tested performance.)

static IEnumerable<int> EnumerateDigits(int value, int baseValue = 10)
{
    while (value > 0)
    {
        yield return value % baseValue;
        value = value / baseValue
    }
}

Then, if you want to switch the order into an array

var t = EnumerateDigits(numbers[i]).Reverse().ToArray();

But, if you just want to sum the digits.

var checksum = EnumerateDigits(numbers[i]).Sum()
Jodrell
  • 34,946
  • 5
  • 87
  • 124