0 امتیاز
سلام دوستان وقت بخیر

من میخوام داخل یک تکست باکس عبارت مثلا 4+2 رو قرار بدم (تکست باکس حالت فرمولی داشته باشه یعنی هر حالت چهار عمل اصلی رو بتونم بدم)  و در تکست باکس دیگم حاصل جمع 6 رو بهم بده ممنون اگه راهنمایی کنید. با تشکر
بسته شده

2 پاسخ

+2 امتیاز
 
بهترین پاسخ
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace MathsEvaluatorDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static class MathsEvaluator
        {
            public static decimal Parse(string expression)
            {
                decimal d;
                if (decimal.TryParse(expression, out d))
                {
                    //The expression is a decimal number, so we are just returning it
                    return d;
                }
                else
                {
                    return CalculateValue(expression);
                }
            }

            public static bool TryParse(string expression, out decimal value)
            {
                if (IsExpression(expression))
                {
                    try
                    {
                        value = Parse(expression);
                        return true;
                    }
                    catch
                    {
                        value = 0;
                        return false;
                    }
                }
                else
                {
                    value = 0;
                    return false;
                }
            }

            public static bool IsExpression(string s)
            {
                //Determines whether the string contains illegal characters
                Regex RgxUrl = new Regex("^[0-9+*-/^()., ]+$");
                return RgxUrl.IsMatch(s);
            }

            private static List<string> TokenizeExpression(string expression, Dictionary<char, int> operators)
            {
                List<string> elements = new List<string>();
                string currentElement = string.Empty;

                int state = 0;
                /* STATES
                     * 0 - start
                     * 1 - after opening bracket '('
                     * 2 - after closing bracket ')'
                     * */
                int bracketCount = 0;
                for (int i = 0; i < expression.Length; i++)
                {
                    switch (state)
                    {
                        case 0:
                            if (expression[i] == '(')
                            {
                                //Change the state after an opening bracket is received
                                state = 1;
                                bracketCount = 0;
                                if (currentElement != string.Empty)
                                {
                                    //if the currentElement is not empty, then assuming multiplication
                                    elements.Add(currentElement);
                                    elements.Add("*");
                                    currentElement = string.Empty;
                                }
                            }
                            else if (operators.Keys.Contains(expression[i]))
                            {
                                //The current character is an operator
                                elements.Add(currentElement);
                                elements.Add(expression[i].ToString());
                                currentElement = string.Empty;
                            }
                            else if (expression[i] != ' ')
                            {
                                //The current character is neither an operator nor a space
                                currentElement += expression[i];
                            }
                            break;
                        case 1:
                            if (expression[i] == '(')
                            {
                                bracketCount++;
                                currentElement += expression[i];
                            }
                            else if (expression[i] == ')')
                            {
                                if (bracketCount == 0)
                                {
                                    state = 2;
                                }
                                else
                                {
                                    bracketCount--;
                                    currentElement += expression[i];
                                }
                            }
                            else if (expression[i] != ' ')
                            {
                                //Add the character to the current element, omitting spaces
                                currentElement += expression[i];
                            }
                            break;
                        case 2:
                            if (operators.Keys.Contains(expression[i]))
                            {
                                //The current character is an operator
                                state = 0;
                                elements.Add(currentElement);
                                currentElement = string.Empty;
                                elements.Add(expression[i].ToString());
                            }
                            else if (expression[i] != ' ')
                            {
                                elements.Add(currentElement);
                                elements.Add("*");
                                currentElement = string.Empty;


                                if (expression[i] == '(')
                                {
                                    state = 1;
                                    bracketCount = 0;
                                }
                                else
                                {
                                    currentElement += expression[i];
                                    state = 0;
                                }
                            }
                            break;
                    }
                }

                //Add the last element (which follows the last operation) to the list
                if (currentElement.Length > 0)
                {
                    elements.Add(currentElement);
                }

                return elements;
            }


            private static decimal CalculateValue(string expression)
            {
                //Dictionary to store the supported operations
                //Key: Operation; Value: Precedence (higher number indicates higher precedence)
                Dictionary<char, int> operators = new Dictionary<char, int>
            {
                {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 3}
            };

                //Tokenize the expression
                List<string> elements = TokenizeExpression(expression, operators);

                //define a value which will be used as the return value of the function
                decimal value = 0;

                //loop from the highest precedence to the lowest
                for (int i = operators.Values.Max(); i >= operators.Values.Min(); i--)
                {

                    //loop while there are any operators left in the list from the current precedence level
                    while (elements.Count >= 3
                        && elements.Any(element => element.Length == 1 &&
                            operators.Where(op => op.Value == i)
                            .Select(op => op.Key).Contains(element[0])))
                    {
                        //get the position of this element
                        int pos = elements
                            .FindIndex(element => element.Length == 1 &&
                            operators.Where(op => op.Value == i)
                            .Select(op => op.Key).Contains(element[0]));

                        //evaluate it's value
                        value = EvaluateOperation(elements[pos], elements[pos - 1], elements[pos + 1]);
                        //change the first operand of the operation to the calculated value of the operation
                        elements[pos - 1] = value.ToString();
                        //remove the operator and the second operand from the list
                        elements.RemoveRange(pos, 2);
                    }
                }

                return value;
            }


            private static decimal EvaluateOperation(string oper, string operand1, string operand2)
            {
                if (oper.Length == 1)
                {
                    decimal op1 = Parse(operand1);
                    decimal op2 = Parse(operand2);

                    decimal value = 0;
                    switch (oper[0])
                    {
                        case '+':
                            value = op1 + op2;
                            break;
                        case '-':
                            value = op1 - op2;
                            break;
                        case '*':
                            value = op1 * op2;
                            break;
                        case '/':
                            value = op1 / op2;
                            break;
                        case '^':
                            value = Convert.ToDecimal(Math.Pow(Convert.ToDouble(op1), Convert.ToDouble(op2)));
                            break;
                        default:
                            throw new ArgumentException("Unsupported operator");
                    }
                    return value;
                }
                else
                {
                    throw new ArgumentException("Unsupported operator");
                }
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            decimal d;
            if (MathsEvaluator.TryParse(textBox1.Text, out d))
            {
                textBox2.Text = "equals: " + d.ToString();
            }
            else
            {
                textBox2.Text = "Unable to evaluate expression, possible incorrect syntax.";
            }
        }
    }
}

 

واقعا دستت درد نکنه کارم راه افتاد smiley

توسط (113 امتیاز) 3
+1 امتیاز

سلام

اینو داخل باتن بزارید 2 تا تکست باکس هست یکی نتیجه و تو یکی هم عمل جمع انجام میشه

 double num;

        private void button1_Click(object sender, EventArgs e)
        {

            num += Convert.ToDouble(textBox1.Text);
          
            textBox2.Text = num.ToString();
            textBox1.Text = "";
        }

 

ممون از اینکه پاسخگو بودین ولی تو این کدی که شما دادین حتما باید اعداد رو یکی یکی به تکست باکست بدی در حالی که من میخواهم مستقیما بتونه مثلا حاصل این عبارت رو که 27 میشه بهم بده 9*(1+2)

آیا تو سی شارپ همچین چیزی وجود داره یا نه؟

ویرایش شده توسط
توسط (113 امتیاز) 3
سوال جدید

2,337 سوال

2,871 پاسخ

3,725 دیدگاه

3,921 کاربر

دسته بندی ها

...