<untitled> (C++)
Ревизии: current
#include <fstream>
#include <string>
#include <stack>
#include <math.h>
using namespace std;
ifstream in;
ofstream out;
stack<char> ops;
stack<double> nums;
string expr;
int len, cur, pr[256];
void no()
{
out << "Error";
exit(0);
}
double get_num()
{
if (nums.empty())
no();
double t = nums.top();
nums.pop();
return t;
}
void do_op()
{
if (ops.empty())
no();
char op = ops.top();
ops.pop();
double x, y;
y = get_num();
if (op == '+' || op == '-' || op == '*' || op == '/')
x = get_num();
if (op == '+')
nums.push(x+y);
else if (op == '-')
nums.push(x-y);
else if (op == '*')
nums.push(x*y);
else if (op == '/')
{
if (y == 0)
no();
nums.push(x/y);
}
else if (op == 's')
nums.push(sin(y+.0));
else if (op == 'c')
nums.push(cos(y+.0));
}
double read_num()
{
double t = 0, ten = 1;
while (expr[cur] >= '0' && expr[cur] <= '9')
t = t*10 + expr[cur++]-'0';
if (expr[cur] == '.')
{
cur++;
while (expr[cur] >= '0' && expr[cur] <= '9')
{
ten *= 10;
t += (expr[cur++]-'0')/ten;
}
}
return t;
}
void next_token()
{
while (expr[cur] == ' ' || expr[cur] == '\t')
cur++;
if (expr[cur] >= '0' && expr[cur] <= '9')
nums.push(read_num());
else if (expr[cur] == '+' || expr[cur] == '-')
{
while (!ops.empty() && pr[ops.top()] >= pr['+'])
do_op();
ops.push(expr[cur++]);
}
else if (expr[cur] == '*' || expr[cur] == '/')
{
while (!ops.empty() && pr[ops.top()] >= pr['*'])
do_op();
ops.push(expr[cur++]);
}
else if (cur+3 < len && (expr.substr(cur, 4) == "sin(" || expr.substr(cur, 4) == "cos("))
{
while (!ops.empty() && pr[ops.top()] >= pr['s'])
do_op();
ops.push(expr[cur]);
cur += 3;
}
else if (expr[cur] == '(')
{
ops.push('(');
cur++;
}
else if (expr[cur] == ')')
{
while (!ops.empty() && ops.top() != '(')
do_op();
if (ops.top() != '(')
no();
else
ops.pop();
cur++;
}
else
no();
}
int main()
{
in.open("input.txt");
out.open("output.txt");
pr['-'] = pr['+'] = 1;
pr['*'] = pr['/'] = 2;
pr['s'] = pr['c'] = 3;
getline(in, expr);
len = expr.length();
while (cur < len)
next_token();
while (!ops.empty())
if (ops.top() == '(' || ops.top() == ')')
no();
else
do_op();
if (nums.size() != 1)
no();
out.setf(0, ios::floatfield);
out.precision(10);
out << nums.top();
}
Комментарии:
Нет