Problem: Read in a non-negative integer that contains only +,-, *,/, evaluates the expression, calculates the value of the formula, and writes out the algorithm.
Reply:
#include <iostream>
#include <stack>
#include <string>
using namespace Std;
Char precede (char A,char b);
Double operate (double A1,char c,double B1);
int main ()
{
Stack<double> OPND;
Stack<char> optr;
string S;
Char theta,c;
int i,k;
Double A, B;
while (Getline (cin,s), s!= "0")
{
Opnd.push (s[0]-48);
i=0;
C=s[++i];
while (c!= ')
{
if (c== ")
{
C=s[++i];
Continue
}
if (c>= ' 0 ' &&c<= ' 9 ')
{
if (s[i-1]>= ' 0 ' &&s[i-1]<= ' 9 ')//important here, for example, 32 characters are consecutive multiple not individual
{
A=opnd.top () *10+c-48;
Opnd.pop ();
Opnd.push (a);
}
Else
Opnd.push (c-48);
C=s[++i];
}
Else
{
if (Optr.empty ()!=true)
{
Switch (Precede (Optr.top (), C))//Focus: operator precedence
{
Case ' < ': Optr.push (c); c=s[++i];break;//If the previous operator is next to the stack
Case ' > ': Theta=optr.top ();//operation here, and not into the stack, because I am the front character and the following character comparison
Optr.pop (); Only the preceding character precedence well paid operation
A=opnd.top ();
Opnd.pop ();
B=opnd.top ();
Opnd.pop ();
Opnd.push (Operate (b,theta,a));
Break
}
}
Else
{
Optr.push (c);
C=s[++i];
}
}
}
while (Optr.empty ()!=true)//Because I enter a number first, perhaps the last operator left is not processed
{
Theta=optr.top ();
Optr.pop ();
A=opnd.top ();
Opnd.pop ();
B=opnd.top ();
Opnd.pop ();
Opnd.push (Operate (b,theta,a));
}
printf ("%.2lf\n", Opnd.top ());
}
return 0;
}
Char precede (char A,char B)//precedence of the comparison operator
{
if (a== ' + ' | | a== '-')
{
Switch (b)
{
Case ' + ':
Case '-': return ' > ';
Case ' * ':
Case '/': return ' < ';
}
}
if (a== ' * ' | | a== '/')
return ' > ';
}
Double operate (double A,char c,double B)//operation
{
Switch (c)
{
Case ' + ': return (A+B);
Case '-': return (A-B);
Case ' * ': return a*b;break;
Case '/': return a/b;break;
}
}
Simple calculator problem