Esempio n. 1
0
        /// <summary>
        /// Получение дробной части числа из str
        /// </summary>
        /// <returns></returns>
        private static string GetMod(string str)
        {
            try
            {
                string rez = BigNumber.Mod(str);
                if (!ExpressionVerifier.IsDecNumber(rez))
                {
                    throw new Exception();
                }

                return(rez);
            }
            catch
            {
                return("-1");
            }
        }
Esempio n. 2
0
        // Кнопка "Вычислить"
        private void buttonRun_Click(object sender, EventArgs e)
        {
            Perevod perevod;                                // Переменная для класса перевода кодировок
            string  text    = textOperation.Text.ToUpper(); // строка пользователя без пробелов и в верхнем регистре
            var     ptext   = new string[100];              // массив элементов строки в обратной польской записи
            int     ptn     = 0;                            // указатель для работы с этим массивом
            var     stec    = new char[100];                // стек для (, ), +, -, * и / (исп. при получении ptext)
            int     stn     = 0;                            // укзатель для работы с этим стеком
            var     stecStr = new string[100];              // стек для чисел и знаков (исп. для получения rezult)
            int     ssn     = 0;                            // укзатель для работы с этим стеком

            // Убирание пробелов из выражения
            while (text.IndexOf(' ') > -1)
            {
                text = text.Replace(" ", string.Empty);
            }

            // Если строка для вычисления не пуста, то начинаем с ней работать
            if (text.Length > 0)
            {
                // Вставление 0 перед унарным минусом в начале выражения
                if (text[0] == '-' || text[0] == '+')
                {
                    text = "0" + text;
                }

                string temp = text[0].ToString();
                // Вставление 0 перед унарным минусом после открывающей скобки
                for (int i = 1; i < text.Length; i++)
                {
                    if (ExpressionVerifier.IsOpenBracket(text[i - 1]) && (text[i] == '-' || text[i] == '+'))
                    {
                        temp += "0" + text[i];
                    }
                    else
                    {
                        temp += text[i];
                    }
                }

                text = temp;
            }
            else
            { // Если строка оказалась пустой, то выходим
                textOperation.Focus();
                textResult.Text = string.Empty;
                return;
            }

            // Проверяем наше выражение на синтаксическую правильность
            var verifier = new ExpressionVerifier(text);

            switch (verifier.Verify())
            {
            case 1:
                textResult.Text = "Error: placing brackets";
                textOperation.Focus();
                return;

            case 2:
                textResult.Text = "Error: quantity character";
                textOperation.Focus();
                return;

            case 3:
                textResult.Text = "Error: writing numbers";
                textOperation.Focus();
                return;

            case 4:
                textResult.Text = "Error: unknown symbol";
                textOperation.Focus();
                return;

            case 5:
                textResult.Text = "Error: syntax expression";
                textOperation.Focus();
                return;
            }

            // Получаем строку в обратной польской записи
            for (int i = 0; i < text.Length; i++)
            {
                if (ExpressionVerifier.IsDigit(text[i]))
                {
                    while (i < text.Length && (ExpressionVerifier.IsDigit(text[i]) || ExpressionVerifier.IsSeparator(text[i])))
                    {
                        ptext[ptn] += text[i++];
                    }

                    perevod    = new Perevod(ptext[ptn]);
                    ptext[ptn] = perevod.ConvertNumberFromCurrentNotationToDec(_notation);
                    if (ptext[ptn].Length > 5 && ptext[ptn].Substring(0, 5).Equals("Error"))
                    {
                        textResult.Text = ptext[ptn];
                        textOperation.Focus();
                        return;
                    }

                    ptn++;
                    i--;
                }
                else if (ExpressionVerifier.IsOpenBracket(text[i]))
                {
                    stec[stn++] = text[i];
                }
                else if (ExpressionVerifier.IsCloseBracket(text[i]))
                {
                    stn--;
                    while (!ExpressionVerifier.IsOpenBracket(stec[stn]))
                    {
                        ptext[ptn++] += stec[stn--];
                    }
                }
                else
                {
                    switch (text[i])
                    {
                    case '+':
                    case '-':
                        if (stn == 0 || ExpressionVerifier.IsOpenBracket(stec[stn - 1]))
                        {
                            stec[stn++] = text[i];
                        }
                        else
                        {
                            stn--;
                            while (stn != -1 && !ExpressionVerifier.IsOpenBracket(stec[stn]))
                            {
                                ptext[ptn++] += stec[stn--];
                            }
                            stn++;
                            stec[stn++] = text[i];
                        }
                        break;

                    case '*':
                    case '/':
                    case '%':
                        if (stn == 0 || ExpressionVerifier.IsOpenBracket(stec[stn - 1]) || stec[stn - 1] == '+' || stec[stn - 1] == '-')
                        {
                            stec[stn++] = text[i];
                        }
                        else
                        {
                            stn--;
                            while (stn != -1 && !ExpressionVerifier.IsOpenBracket(stec[stn]) && stec[stn] != '+' && stec[stn] != '-')
                            {
                                ptext[ptn++] += stec[stn--];
                            }
                            stn++;
                            stec[stn++] = text[i];
                        }
                        break;

                    case '^':
                        if (stn == 0 || ExpressionVerifier.IsOpenBracket(stec[stn - 1]) || stec[stn - 1] == '+' || stec[stn - 1] == '-' || stec[stn - 1] == '*' || stec[stn - 1] == '/')
                        {
                            stec[stn++] = text[i];
                        }
                        else
                        {
                            stn--;
                            while (stn != 0 && !ExpressionVerifier.IsOpenBracket(stec[stn]) && stec[stn] != '+' && stec[stn] != '-' && stec[stn] != '*' && stec[stn] != '/')
                            {
                                ptext[ptn++] += stec[stn--];
                            }
                            stn++;
                            stec[stn++] = text[i];
                        }
                        break;
                    }
                }
            }

            for (int i = stn - 1; i >= 0; i--)
            {
                ptext[ptn++] += stec[i];
            }

            // Вычисляем выражение, записанное в обратной польской записи
            BigNumber c;

            for (int i = 0; i < ptn; i++)
            {
                if (ExpressionVerifier.IsDigit(Convert.ToChar(ptext[i].Substring(0, 1))))
                {
                    stecStr[ssn++] = ptext[i];
                }
                else
                {
                    var a = new BigNumber(ExpressionVerifier.RemoveBeganZerosFromNumber(stecStr[ssn - 2]));
                    var b = new BigNumber(ExpressionVerifier.RemoveBeganZerosFromNumber(stecStr[ssn - 1]));

                    switch (Convert.ToChar(ptext[i].Substring(0, 1)))
                    {
                    case '+':
                        c = a + b;
                        break;

                    case '-':
                        c = a - b;
                        break;

                    case '*':
                        c = a * b;
                        break;

                    case '/':
                        c = a / b;
                        if (c.Value.StartsWith("Error"))
                        {
                            textResult.Text = c.Value;
                            textOperation.Focus();
                            return;
                        }
                        break;

                    case '%':
                        c = a % b;
                        if (c.Value.StartsWith("Error"))
                        {
                            textResult.Text = c.Value;
                            textOperation.Focus();
                            return;
                        }
                        break;

                    case '^':
                        c = a ^ b;
                        break;

                    default:
                        textResult.Text = "Error: RUNTIME ERROR";
                        textOperation.Focus();
                        return;
                    }

                    stecStr[ssn - 2] = c.Value;
                    ssn--;
                }
            }

            if (ssn != 1)
            {
                textResult.Text = "Error: syntax expression";
                textOperation.Focus();
                return;
            }

            perevod         = new Perevod(stecStr[0]);
            textResult.Text = perevod.ConvertNumberFromDecToTargetNotation(_notation);
            textOperation.Focus();
            if (!textResult.Text.StartsWith("Error"))
            {
                var param = new string[2];
                param[0] = textOperation.Text;
                param[1] = textResult.Text;
                List.Rows.Insert(0, param);
            }
        }