-1

I have a task to calculate sum of digits in C#. In this case as an example. I like to calculate the sum of "12345" which is: 1+2+3+4+5 = 15. But the result coming after the execution of code is: 53. What is the mistake in the code?

static void Main(string[] args)
{
    string inputNumber = "12345";

    int sum =0;
    Console.WriteLine("Please Enter Your Desired Number");

    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine(inputNumber[i]);
        sum = sum + Convert.ToInt32(inputNumber[i]);

        Console.WriteLine(sum);
    }
}
maccettura
  • 10,514
  • 3
  • 28
  • 35

3 Answers3

0

Converting a char to an int is not the same as converting a string to an int For char, the ASCII value is used.

sum = sum + Convert.ToInt32(inputNumber[i].ToString());

If you convert your char to a string, it will do what you expect it to do.

Flater
  • 12,908
  • 4
  • 39
  • 62
  • I would add that if you want to be sure you could use `Int32.Parse()` as it would throw an error if you try to enter a char. – vvilin Oct 10 '19 at 17:57
  • @vvilin: I'm on the fence about that approach. Not that it doesn't work, but `Convert.ToFoo` is generally nicer to use than `Foo.Parse`. – Flater Oct 10 '19 at 18:04
  • Thank you for the response. It has helped me resolve the issue. – Muhammad Rehan Oct 10 '19 at 18:09
0

your problem is that "Convert.ToInt32" is returning the ascii value and you are looking for the numeric value, your code could be like this:

sum = sum + Convert.ToInt32(Char.GetNumericValue(inputNumber[i]));

for more information about GetNumericValue here is a link: get numeric value msdn

MorenajeRD
  • 849
  • 1
  • 11
  • 27
-2

Sorry wrong answer.

This is the problem:

Convert.ToInt32(inputNumber[i].ToString());

If you don't cast it to string, it's a char. And convert a char to int will give its ASCII value.

Max
  • 1,068
  • 1
  • 10
  • 15