-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluation.cs
74 lines (66 loc) · 2.17 KB
/
Evaluation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.Text;
namespace AvitCalculator_Exam
{
public class Evaluation
{
public Stack<double> Evaluate(string expression, string[] num)
{
String expr = "(" + expression + ")";
Stack<String> ops = new Stack<String>();
Stack<double> result = new Stack<double>();
foreach (var item in num)
{
result.Push(double.Parse(item));
}
for (int i = 0; i < expr.Length; i++)
{
String strValue = expr.Substring(i, 1);
if (strValue.Equals("("))
{ }
else if (strValue.Equals("+"))
{
ops.Push(strValue);
}
else if (strValue.Equals("-"))
{
ops.Push(strValue);
}
else if (strValue.Equals("*"))
{
ops.Push(strValue);
}
else if (strValue.Equals("/"))
{
ops.Push(strValue);
}
else if (strValue.Equals("sqrt"))
{
ops.Push(strValue);
}
else if (strValue.Equals(")"))
{
int count = ops.Count;
while (count > 0)
{
String operand = ops.Pop();
double ans = result.Pop();
ans = operand switch
{
"-" => result.Pop() - ans,
"+" => result.Pop() + ans,
"/" => result.Pop() / ans,
"*" => result.Pop() * ans,
"sqrt" => Math.Sqrt(ans),
_ => 0,
};
result.Push(ans);
count--;
}
}
}
return result;
}
}
}