对于练习作业,我需要创建一个计算器,它可以:
- 乘
- 划分
- 添加
- 减去
- 处理小数
- 处理负数,例如 (2--3=5)
除了处理负数之外,我已经完成了所有工作,我真的不知道如何做这样的事情,并认为你可以提供帮助。这是我当前的解决代码:
public decimal getResult(string equation)
{
//parse a equation as a string and solve it
List<string> numbers = input.Split(opSplit, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
List<string> operators = input.Split(numSplit, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
//remove any decimals from operators list
for (int i = 0; i < operators.Count; i++)
{
if (operators[i] == ".")
{
operators.RemoveAt(i);
}
}
//set total to first values in numbers then remove in from list
decimal total = decimal.Parse(numbers[0]);
numbers.Remove(total.ToString());
int count = 0;
foreach(string s in numbers) {
decimal val = decimal.Parse(s);
string current_operator = operators[count];
MessageBox.Show(current_operator);
switch (current_operator)
{
case "+":
total += val;
break;
case "-":
total -= val;
break;
case "x":
total *= val;
break;
case "/":
total /= val;
break;
}
if (count != operators.Count-1)
{
count++;
}
}
return total;
}
我的方程式是以这种格式输入的。
- 1+2-3*4/5