M
M
Mykola Franchuk2016-03-29 01:53:20
C++ / C#
Mykola Franchuk, 2016-03-29 01:53:20

Why does one branch of the code in the program not work?

Hello, I decided to solve a couple of Olympiad problems, I came across one of the simplest ones, where you need to solve a linear equation with one variable and numbers from 0 to 9 (therefore, the algorithm shamelessly tied to positions). And in one of the branches of the code ( x = equation[4] + equation[2]; ), something completely different happens. If you enter x-1=7, it outputs 104, but you need, of course, 8.

Console.WriteLine("Введите уравнение: ");
        string equation = Console.ReadLine();
        int x;
        if (!Char.IsDigit(equation[0]))
        {
            if (equation[1] == '+')
            {
                x = equation[4] - equation[2];
            }
            else
            {
                x = equation[4] + equation[2];
            }
        }
        else
        {
            if (equation[1] == '+')
            {
                x = equation[4] - equation[0];
            }
            else
            {
                x = -(equation[4] - equation[0]);
            }
        }
        Console.WriteLine("x: " + x);

The usual Olympiad problem, everything seems to be obvious, but the second branch of the code desperately does not want to work. Tell me where I went wrong, I have no ideas at all.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
akass, 2016-03-29
@kuzia_bRatok

Everything works as it should, just go through the steps in debugging.
You didn't convert strings to numbers. Therefore, the compiler takes the character code from the su0.ru/WlLx
table, the integer code of the seven is 55, the code of the unit is 49, in total 104. So everything is correct.
For example, this will work as you want, but of course this is not the right way to do it.
x = Convert.ToInt32(equation[4].ToString()) + Convert.ToInt32(equation[2].ToString());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question