演習課題では、次のことができる電卓を作成する必要があります。
- かける
- 分ける
- 追加
- 減算
- 小数の処理
- 負の数の処理 (例: (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