|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplicationCal
{
class Program
{
private static char[,] Precede_Matrix = new char[7, 7]
{
{'>', '>', '<', '<', '<', '>', '>',},
{'>', '>', '<', '<', '<', '>', '>',},
{'>', '>', '>', '>', '<', '>', '>',},
{'>', '>', '>', '>', '<', '>', '>',},
{'<', '<', '<', '<', '<', '=', '0',},
{'>', '>', '>', '>', '0', '>', '>',},
{'<', '<', '<', '<', '<', '0', '=',}
};
public static char Precede(char a, char b)
{
int i = 0;
int j = 0;
switch (a)
{
case '+': i = 0; break;
case '-': i = 1; break;
case '*': i = 2; break;
case '/': i = 3; break;
case '(': i = 4; break;
case ')': i = 5; break;
case '#': i = 6; break;
default: break;
}
switch (b)
{
case '+': j = 0; break;
case '-': j = 1; break;
case '*': j = 2; break;
case '/': j = 3; break;
case '(': j = 4; break;
case ')': j = 5; break;
case '#': j = 6; break;
default: break;
}
return (Precede_Matrix[i, j]);
}
public static double Operate(double a, char oper, double b)
{
switch (oper)
{
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return -1;
}
}
public static bool IsOperand(char c)
{
if (('0' <= c && c <= '9') || c == '.') // c是数字或小数点
return true;
else
return false;
}
static void Main(string[] args)
{
string str;
while ((str = Console.ReadLine()) != null)
{
str += "#"; // 后是#(结束标志)
double a;
double b;
char x;
char theta;
Stack OPTR = new Stack();
OPTR.Push('#');
Stack OPND = new Stack();
int i = 0;
char c = str[i++];
double operand = 0;
while (!(c == '#' && OPTR.Peek() == '#'))
{
if (IsOperand(c)) // c是数字或小数点(这里一定是数字),小数点已在下面转换掉了
{
int startIndex = i - 1;
int length = 1; // c是数字,故初始一定是1
while (IsOperand(str[i]))
{
i++;
length++;
}
string doubleString = str.Substring(startIndex, length);
// operand = atof(&str[i - 1]); // 把从c开头的数转化成double
OPND.Push(double.Parse(doubleString));
c = str[i++];
}
else // c is operator or delimiter
{
switch (Precede(OPTR.Peek(), c))
{
case '<':
OPTR.Push(c);
c = str[i++];
break;
case '=':
x = OPTR.Pop();
c = str[i++];
break;
case '>':
theta = OPTR.Pop();
b = OPND.Pop();
a = OPND.Pop();
OPND.Push(Operate(a, theta, b));
break;
default:
break;
}
}
}
// OPTR栈的栈顶元素和当前读入的字符均为“#”
// 即“#”=“#”时整个表达式求值完毕
Console.WriteLine(OPND.Peek());
}
}
}
}
|