public double Calculate(Stack <Actions> actions, Stack <string> operands, string reverseNotation) { Stack <double> numbers = GetConvertStack(operands); Stack <double> result = new Stack <double>(); for (int i = 0; i < reverseNotation.Length; i++) { string word = ""; while (i < reverseNotation.Length && reverseNotation[i] != ' ') { word += reverseNotation[i++]; } if (!actions.IsEmpty() && word == actions.Top().Name) { ProcessOperation(actions.Top(), result); actions.Pop(); } else { result.Push(numbers.Top()); numbers.Pop(); } } return(result.Top()); }
private void AddOperationToStack(Stack <Actions> functions, string line, int curIndex, ref string result, Stack <Actions> actions) { string op = ""; op += line[curIndex]; int priopity; if (IsUnaryOperation(line, curIndex, functions)) { priopity = 4; } else { priopity = GetPriorityOperation(op); } while (!functions.IsEmpty() && (functions.Top().IsFunction || priopity < functions.Top().Priority)) { result += functions.Top().Name; actions.Push(functions.Top()); result += ' '; functions.Pop(); } functions.Push(new Actions(op, false, priopity)); }
private Stack <double> GetConvertStack(Stack <string> operands) { Stack <double> result = new Stack <double>(); while (!operands.IsEmpty()) { if (!(operands.Top() == "pi" || operands.Top() == "e")) { result.Push(double.Parse(operands.Top())); } else { if (operands.Top() == "pi") { result.Push(Math.PI); } else { result.Push(Math.E); } } operands.Pop(); } return(result.ReverseStack()); }
private void Transfer(List <String> str) //中缀转化为后缀,存在sharedExp中 { Node currentNode; char ch, temp = '\0'; double op = 0; int length, n = 1; length = readInExp.Modify(str); chStack.Push('#', 0); while (true) { currentNode = readInExp.GetNode(n); ch = currentNode.ch; op = currentNode.op; if (ch == '\0') { sharedExp.LinkNode(ch, op); } else if (ch == ')') { for (chStack.Top(ref temp, ref op), chStack.Pop(); temp != '('; chStack.Top(ref temp, ref op), chStack.Pop()) { sharedExp.LinkNode(temp, 0); } }//end else if else { for (chStack.Top(ref temp, ref op), chStack.Pop(); Icp(ch) <= Isp(temp); chStack.Top(ref temp, ref op), chStack.Pop()) { sharedExp.LinkNode(temp, 0); } chStack.Push(temp, 0); chStack.Push(ch, 0); } if (n == length) { break; } n += 1; }//end while while (!chStack.IsEmpty()) { chStack.Top(ref temp, ref op); chStack.Pop(); if (temp != '#') { sharedExp.LinkNode(temp, 0); } } }//end method
private string[] ToPolish() { var output = new string[_parsed.Length]; int i = 0; var stack = new Stack<string>(); foreach (var str in _parsed) { if (str == null) break; double x; //почему-то дробные числа записанные через точку - не парсит //если писать через запятую - все в порядке if (double.TryParse(str, out x)) { output[i++] = str; } else { if (str == "(") { stack.Push(str); } else if (str == ")") { while (stack.Top() != "(") output[i++] = stack.Pop(); stack.Pop(); } else if (str == "*" || str == "/" || str == "+" || str == "-" || str == "^") { while (!stack.Empty() && GetPriority(str) <= GetPriority(stack.Top())) { output[i++] = stack.Pop(); } stack.Push(str); } } } while (!stack.Empty()) { output[i++] = stack.Pop(); } return output; }
private void AddFunctionsAndOperations(Stack <Actions> functions, ref string result, Stack <Actions> actions) { while (!functions.IsEmpty() && functions.Top().Name != "(") { result += functions.Top().Name; actions.Push(functions.Top()); result += ' '; functions.Pop(); } if (!functions.IsEmpty() && functions.Top().Name == "(") { functions.Pop(); if (!functions.IsEmpty() && functions.Top().IsFunction) { result += functions.Top().Name; actions.Push(functions.Top()); result += ' '; functions.Pop(); } } else { throw new Exception("Строка не корректно задана"); } }
private void AddFunctionsAndOperations(Stack <Actions> functions, ref string result, Stack <Actions> actions) { while (!functions.IsEmpty() && functions.Top().Name != "(") { result += functions.Top().Name; actions.Push(functions.Top()); result += ' '; functions.Pop(); } if (!functions.IsEmpty() && functions.Top().Name == "(") { functions.Pop(); if (!functions.IsEmpty() && functions.Top().IsFunction) { result += functions.Top().Name; actions.Push(functions.Top()); result += ' '; functions.Pop(); } } else { throw new Exception("The string is set incorrectly"); } }
public Pair Run(List <String> str) { Transfer(str); Node currentNode; char ch = '\0'; double op = 0.0; int length, n = 1; length = sharedExp.length; while (n <= length) { currentNode = sharedExp.GetNode(n); ch = currentNode.ch; op = currentNode.op; if (ch == '\0') { PushOperand(op); } else { if (DoOperator(ch)) { } else { answer.answer = 0; answer.flag = false; return(answer); } } n += 1; } if (opStack.Top(ref ch, ref op)) { answer.answer = op; answer.flag = true; return(answer); } answer.answer = 0; answer.flag = false; return(answer); }//end of method
public void SolvePosfix(string posfix) { string[] containValues = posfix.Split(' '); Stack <string> containResult = new Stack <string>(); for (int i = 0; i < containValues.Length - 1; i++) { if (!LaToanTu(containValues[i][0])) { containResult.Push(containValues[i]); } else { string a = containResult.Top(); containResult.Pop(); string b = containResult.Top(); containResult.Pop(); containResult.Push(Calculate(containValues[i], b, a)); } } double kq = Convert.ToDouble(containResult.Top()); textBox1.Text = Convert.ToString(kq); }
private void ProcessOperation(Actions action, Stack <double> results) { switch (action.Name) { case "+": double num1 = results.Top(); results.Pop(); double num2 = results.Top(); results.Pop(); results.Push(num2 + num1); return; case "/": num1 = results.Top(); results.Pop(); if (num1 == 0) { throw new Exception("Ошибка деления на нуль"); } num2 = results.Top(); results.Pop(); results.Push(num2 / num1); return; case "*": num1 = results.Top(); results.Pop(); num2 = results.Top(); results.Pop(); results.Push(num2 * num1); return; case "-" when action.Priority == 1: num1 = results.Top(); results.Pop(); num2 = results.Top(); results.Pop(); results.Push(num2 - num1); return; case "-" when action.Priority == 4: num1 = results.Top(); results.Pop(); results.Push(-num1); return; case "^": num1 = results.Top(); results.Pop(); num2 = results.Top(); results.Pop(); results.Push(Math.Pow(num2, num1)); return; case "cos": num1 = results.Top(); results.Pop(); results.Push(Math.Cos(num1)); return; case "sin": num1 = results.Top(); results.Pop(); results.Push(Math.Sin(num1)); return; case "tg": num1 = results.Top(); if (num1 % Math.PI == Math.PI / 2) { throw new Exception("Не существующий тангенс"); } results.Pop(); results.Push(Math.Tan(num1)); return; case "ctg": num1 = results.Top(); if (num1 % Math.PI == 0) { throw new Exception("Не существующий катангенс"); } results.Pop(); results.Push(1 / Math.Tan(num1)); return; case "ln": num1 = results.Top(); if (num1 <= 0) { throw new Exception("Не существующий логарифм"); } results.Pop(); results.Push(Math.Log(num1, Math.E)); return; case "log": num1 = results.Top(); results.Pop(); num2 = results.Top(); if (num2 <= 0 || num1 <= 0 || num2 == 1) { throw new Exception("Не существующий логарифм"); } results.Pop(); results.Push(Math.Log(num1, num2)); return; case "sqrt": num1 = results.Top(); if (num1 < 0) { throw new Exception("Число под корнем меньше нуля"); } results.Pop(); results.Push(Math.Sqrt(num1)); return; case "sqr": num1 = results.Top(); results.Pop(); results.Push(Math.Pow(num1, 2)); return; } }
public string GetReverseNotation(string line, out Stack <Actions> actions, out Stack <string> operands) { string result = ""; actions = new Stack <Actions>(); operands = new Stack <string>(); Stack <Actions> functions = new Stack <Actions>(); for (int i = 0; i < line.Length; i++) { if (IsSplite(line[i])) { continue; } if (IsDigit(line[i]) && (i == 0 || line[i - 1] != '.')) { AddDigits(ref result, line, ref i, operands); continue; } if (line[i] == '(') { functions.Push(new Actions("(", false, -1)); continue; } if (line[i] == ')') { AddFunctionsAndOperations(functions, ref result, actions); continue; } if (IsBinaryOperation(line, i)) { AddOperationToStack(functions, line, i, ref result, actions); continue; } if (IsConstant(line, ref i, ref result, operands)) { continue; } AddFunctionToStack(functions, line, ref i); } while (!functions.IsEmpty()) { if (!IsFunction(functions.Top().Name) && (functions.Top().Name.Length == 0 || functions.Top().Name[0] != '+' && functions.Top().Name[0] != '-' && functions.Top().Name[0] != '*' && functions.Top().Name[0] != '/' && functions.Top().Name[0] != '^')) { throw new Exception("Строка не корректно задана"); } result += functions.Top().Name; actions.Push(functions.Top()); result += ' '; functions.Pop(); } actions = actions.ReverseStack(); operands = operands.ReverseStack(); return(result); }
public string calculating(string str1) //计算输入式 { double newop = 0; List <String> str2; str2 = infixToPostfix(str1.ToCharArray()); //获取中缀表达式 foreach (String str3 in str2) { if (str3.Length == 1) { switch (str3.ToCharArray()[0]) { case '+': case '-': case '*': case '/': case '^': DoOperator(str3.ToCharArray()[0]); break; default: PushOperand((double)(str3.ToCharArray()[0] - '0')); break; } } else { char[] operand1 = str3.ToCharArray(); double sum = 0; int n = 0; bool dot = false; for (int i = 0; i < operand1.Length && (operand1[i] >= '0' && operand1[i] <= '9' || operand1[i] == '.'); i++) { if (operand1[i] == '.') //判断是否有小数点 { dot = true; continue; } if (!dot) { sum = sum * 10 + (operand1[i] - '0'); //算整数 } else //加上小数 { sum = sum + (operand1[i] - '0') * Math.Pow(10, -++n); } Console.WriteLine(sum); } Console.WriteLine(); PushOperand(sum); } } if (Form1.str.Equals("错误")) { return(null); } if (s.Top(ref newop)) { return(newop.ToString()); } return(null); }
private List <String> infixToPostfix(char[] operand) //中缀表达式转换为后缀表达式 { List <String> str1 = new List <string>(); //因数及运算符存储 Stack <char> s = new Stack <char>(); char y = '\0'; s.Push('#'); //#号作为结束的标志 for (int i = 0; i < operand.Length; i++) { if (operand[i] >= '0' && operand[i] <= '9') { double sum = 0, //运算符边的数字 sum1 = 0; //运算符边的数字 int n = 0; bool dot = false; //判断是否有小数点 bool mod = false; //判断是否有模运算 for (; i < operand.Length && (operand[i] >= '0' && operand[i] <= '9' || operand[i] == '.' || operand[i] == '!' || operand[i] == '%'); i++) { if (operand[i] == '.')//判断是否有小数点 { dot = true; continue; } if (operand[i] == '!') //计算阶乘 { if (!dot) { sum = factorial(sum); //判断,小数没有阶乘 } else { Form1.str = "错误"; } continue; } if (operand[i] == '%') //判断是否有模运算 { mod = true; sum1 = sum; sum = 0; continue; } if (!dot) { sum = sum * 10 + (operand[i] - '0'); //算整数 } else //加上小数 { sum = sum + (operand[i] - '0') * Math.Pow(10, -++n); } if (mod) { if ((i + 1) < operand.Length && (operand[i + 1] >= '0' && operand[i + 1] <= '9' || operand[i + 1] == '.' || operand[i + 1] == '!' || operand[i + 1] == '%')) { ; } else if (sum >= 1) { sum = (int)sum1 % (int)sum; } else { Form1.str = "错误"; } } } i--; //把多增加的i减回来 str1.Add(sum.ToString()); } else if (operand[i] == '√') //求根号 { double sum = 0; int n = 0; bool dot = false; for (i++; i < operand.Length && (operand[i] >= '0' && operand[i] <= '9' || operand[i] == '.' || operand[i] == '!'); i++) { if (operand[i] == '.')//判断是否有小数点 { dot = true; continue; } if (operand[i] == '!') //计算阶乘 { if (!dot) { sum = factorial(sum); //判断,小数没有阶乘 } else { Form1.str = "错误"; } continue; } if (!dot) { sum = sum * 10 + (operand[i] - '0'); //算整数 } else //加上小数 { sum = sum + (operand[i] - '0') * Math.Pow(10, -++n); } } sum = Math.Sqrt(sum); //求根号 i--; //把多增加的i减回来 str1.Add(sum.ToString()); } else if (operand[i] == ')') { for (s.Top(ref y), s.Pop(); y != '('; s.Top(ref y), s.Pop()) { str1.Add(y.ToString()); } } else { for (s.Top(ref y), s.Pop(); icp(operand[i]) <= isp(y); s.Top(ref y), s.Pop()) { str1.Add(y.ToString()); } s.Push(y); s.Push(operand[i]); } } while (!s.IsEmpty()) { s.Top(ref y); s.Pop(); if (y != '#') { str1.Add(y.ToString()); } } return(str1); }
private void ProcessOperation(Actions action, Stack <double> results) { switch (action.Name) { case "+": double num1 = results.Top(); results.Pop(); double num2 = results.Top(); results.Pop(); results.Push(num2 + num1); return; case "/": num1 = results.Top(); results.Pop(); if (num1 == 0) { throw new Exception("Division by zero error"); } num2 = results.Top(); results.Pop(); results.Push(num2 / num1); return; case "*": num1 = results.Top(); results.Pop(); num2 = results.Top(); results.Pop(); results.Push(num2 * num1); return; case "-" when action.Priority == 1: num1 = results.Top(); results.Pop(); num2 = results.Top(); results.Pop(); results.Push(num2 - num1); return; case "-" when action.Priority == 4: num1 = results.Top(); results.Pop(); results.Push(-num1); return; case "^": num1 = results.Top(); results.Pop(); num2 = results.Top(); results.Pop(); results.Push(Math.Pow(num2, num1)); return; case "cos": num1 = results.Top(); results.Pop(); results.Push(Math.Cos(num1)); return; case "sin": num1 = results.Top(); results.Pop(); results.Push(Math.Sin(num1)); return; case "tg": num1 = results.Top(); if (num1 % Math.PI == Math.PI / 2) { throw new Exception("Non-existent tangent"); } results.Pop(); results.Push(Math.Tan(num1)); return; case "ctg": num1 = results.Top(); if (num1 % Math.PI == 0) { throw new Exception("Non-existent cotangent"); } results.Pop(); results.Push(1 / Math.Tan(num1)); return; case "ln": num1 = results.Top(); if (num1 <= 0) { throw new Exception("Non-existent logarithm"); } results.Pop(); results.Push(Math.Log(num1, Math.E)); return; case "log": num1 = results.Top(); results.Pop(); num2 = results.Top(); if (num2 <= 0 || num1 <= 0 || num2 == 1) { throw new Exception("Non-existent logarithm"); } results.Pop(); results.Push(Math.Log(num1, num2)); return; case "sqrt": num1 = results.Top(); if (num1 < 0) { throw new Exception("The number under the root is less than zero"); } results.Pop(); results.Push(Math.Sqrt(num1)); return; case "sqr": num1 = results.Top(); results.Pop(); results.Push(Math.Pow(num1, 2)); return; } }
private double GetResult() { var stack = new Stack<string>(); //обрабатываем массив foreach (var str in _polishNotation) { if (str == null) break; if (GetPriority(str) == -1) stack.Push(str); else if (str == "*" || str == "/" || str == "+" || str == "-" || str == "^") { double first = 0, second = 0; double.TryParse(stack.Pop(), out second); double.TryParse(stack.Pop(), out first); switch (str) { case "+": stack.Push((first + second).ToString(CultureInfo.InvariantCulture)); break; case "-": stack.Push((first - second).ToString(CultureInfo.InvariantCulture)); break; case "*": stack.Push((first * second).ToString(CultureInfo.InvariantCulture)); break; case "/": stack.Push((first / second).ToString(CultureInfo.InvariantCulture)); break; case "^": stack.Push(Math.Pow(first, second).ToString(CultureInfo.InvariantCulture)); break; } } //Console.WriteLine(stack.top()); } double result; if ((stack.GetSize() != 1) || !double.TryParse(stack.Top(), out result)) { //Console.WriteLine("Incorrect Input"); throw new IndexOutOfRangeException(); } return result; }
public string MidtoPosfix() { Stack <string> a = new Stack <string>(); string ketQuaHauTo = ""; string tokken; string nhap = textBox1.Text; nhap = nhap.Trim(); string s = ""; for (int i = 0; i < nhap.Length; i++) { if (nhap[i] != ' ') { s += nhap[i]; } } int demMoNgoac = 0; int demDongNgoac = 0; int demToanTu = 0; int demToanHang = 0; for (int i = 0; i < s.Length;) { GetTokken(s, out tokken, ref i); if (tokken[0] == '(') { demMoNgoac++; } else if (tokken[0] == ')') { demDongNgoac++; } else if (LaToanTu(tokken[0])) { demToanTu++; } else { demToanHang++; } } if (demDongNgoac == demMoNgoac && demToanHang - 1 == demToanTu) { for (int i = 0; i < s.Length;) { GetTokken(s, out tokken, ref i); if (!LaToanTu(tokken[0])) { ketQuaHauTo += tokken + " "; } else { if (tokken[0] == '(') { a.Push(tokken); } else if (tokken[0] == ')') { while (a.Top()[0] != '(') { ketQuaHauTo += a.Top() + " "; a.Pop(); } if (a.Top()[0] == '(') { a.Pop(); } } else { if (!a.IsEmpty() && DoUuTien(a.Top()[0]) < DoUuTien(tokken[0])) { a.Push(tokken); continue; } else if (a.IsEmpty()) { a.Push(tokken); continue; } while (!a.IsEmpty() && DoUuTien(a.Top()[0]) >= DoUuTien(tokken[0])) { ketQuaHauTo += a.Top() + " "; a.Pop(); } a.Push(tokken); } } } while (!a.IsEmpty()) { if (a.Top()[0] == '(') { a.Pop(); continue; } ketQuaHauTo += a.Top() + " "; a.Pop(); } return(ketQuaHauTo); } else { return("\nBieu thuc sai"); } }
private bool IsUnaryOperation(string line, int index, Stack <Actions> functions) { return(index == 0 || IsBinaryOperation(line, index - 1) || line[index - 1] == '(' || !functions.IsEmpty() && functions.Top().IsFunction); }