C#中如何在一个文本框中实现加减乘除的运算?

2024-12-16 13:35:50
推荐回答(5个)
回答1:

List lists = null;
private void button1_Click(object sender, EventArgs e)
{
lists = new List();
string str = textBox1.Text;
string temp = "";
int index = 0, sum = str.Length;

foreach (char c in str)
{
index++;
if (c != '+' && c != '-' && c != '*' && c != '/')
{
temp += c;
}
else
{
lists.Add(temp);
lists.Add(c.ToString());
temp = "";
}

if (index == sum)
{
lists.Add(temp);
}
}

index = 0;
do
{
string type1 = lists[index + 1];

if (type1 == "+" || type1 == "-")
{

if (lists.Count < 4)
{
Make(index, lists[index], lists[index + 2], type1);
}
else
{
string type2 = lists[index + 3];
if (type2 == "*" || type2 == "/")
{
Make(index + 2, lists[index + 2], lists[index + 4], type2);
}
else
{
Make(index, lists[index], lists[index + 2], type1);
}
}
}
else
{
Make(index,lists[index],lists[index + 2],type1);

}
if (lists.Count == 1)
{
textBox2.Text = lists[0];
break;
}
} while (1 == 1);
}

///


/// 计算
///

/// 起始下标
/// 第一个参数
/// 第二个参数
/// 符号
private void Make(int index, string noStr1, string noStr2,string type)
{
double tempSum = 0,no1 = Convert.ToDouble(noStr1),no2 = Convert.ToDouble(noStr2);
switch (type)
{
case "+":
tempSum = no1 + no2;
break;
case "-":
tempSum = no1 - no2;
break;
case "*":
tempSum = no1 * no2;
break;
case "/":
tempSum = no1 / no2;
break;
}

//消除已经计算过的参数,改为一个计算结果
lists[index + 2] = tempSum.ToString();
lists.RemoveAt(index);
lists.RemoveAt(index);
}

在不用括号的情况下,有括号的以后有时间再弄

回答2:

在按钮事件里面:TxtB.Text = (1+2-1*5).ToString();

回答3:

放进数组然后再处理

回答4:

使用栈的算法来实现

回答5:

你想要一个计算起吗? c#的?