Интерпретатор арифметических выражений - C#
Формулировка задачи:
Как сделать калькулятор который мог бы вычислять математические выражения. Например, a+b*(i/2-m)
Программа должна воспринимать любые символы и спрашивать у пользователя их значение. Поделитесь пожалуйста примерами.
Решение задачи: «Интерпретатор арифметических выражений»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OPN_Calc
{
class Program
{
static void Main(string[] args)
{
Console.Write("Введите выражение: ");
string exp = Console.ReadLine();
Console.WriteLine("Ваше выражение в ОПН выглядит так: " + GetExp(exp));
Console.ReadKey();
}
static private string GetExp(string str)
{
string outString = "";
Stack<char> operStack = new Stack<char>();
for (int i = 0; i < str.Length; i++)
{
if (Char.IsDigit(str[i]))
outString += str[i];
else
{
if (str[i] == ' ')
continue;
if (IsPerem(ch))
char per1 = zapros(ch);
static bool IsPerem(char ch)
{
if ("abcdi.....xyz".)IndexOf(с) != -1))
return true;
return false;
}
static char zapros(char ch)
{
Console.Write("Значение переменной {0}:" , ch);
return Console.ReadLine();
}
else if (IsDelim(str[i]))
{
if (operStack.Count > 0)
if (GetPriority(str[i]) <= GetPriority(operStack.Peek()))
outString += operStack.Pop();
operStack.Push(str[i]);
}
else if (str[i] == '(')
operStack.Push(str[i]);
else if (str[i] == ')')
{
char s = operStack.Pop();
while (s != '(')
{
outString += s;
s = operStack.Pop();
}
}
}
Console.WriteLine(outString);
}
while (operStack.Count > 0)
outString += operStack.Pop();
return outString;
}
static private bool IsDelim(char с)
{
if (("+-/*=^".IndexOf(с) != -1))
return true;
return false;
}
static private byte GetPriority(char s)
{
switch (s)
{
case '(':
return 0;
case ')':
return 1;
case '+':
return 2;
case '-':
return 3;
case '*':
return 4;
case '/':
return 4;
case '^':
return 5;
default:
return 6;
}
}
}
}