Как ввести числа с плавающей запятой в стек вычислителя - PullRequest
0 голосов
/ 19 апреля 2020

Я реализовал инфикс для постфикса, а затем калькулятор оценки постфикса, но мне нужно, чтобы он считывал числа с плавающей точкой и рассматривал точку как плавающую точку, а не как оператор из строки, и я действительно очень запутался, надеюсь, вы сможете помогите мне я выложу свой код ниже:

 #include <iostream>
 #include <string>
 #include <stack>
 #include <sstream>

 using namespace std;


bool isDigit(char c) //we check if char is a digit, the ASCII value of '0' = 48, '1' = 49,'9' = 57
{
    if(c >= '0' && c <= '9')
    {
        return true;
    }
    else
    {
        return false;
    }

} // isDi git

int priority(char c) //this function returns the higher priority of the operators
{
    if(c == '-' || c == '+')
    {
       return 1;
    }
    else if(c == '*' || c == '/')
    {
       return 2;
    }
    else if(c == '^')
    {
        return 3;
    }
    else
    {
        return 0;  
    } 

} // приоритет

double mathOperate(double op1, double op2, char op)//arth operations
{
   if(op == '+')
   {
      return op1 + op2;
   }
   else if(op == '-')
   {
      return op1 - op2;
   }
   else if(op == '/')
   {
      return op1 / op2;
   }
   else if(op == '*')
   {
      return op1 * op2;
   }
   else
   {
      return 0;
   }

} // оперируют

   string infix_to_postfix(string exp) //this function returns our postfix value
   {
      stack<char> oper; // This is the stack we are going to put our operators in
      string output = "";

for(int i = 0; i < exp.length(); i++) // this loop will check every element in our string
{       
    if(exp[i] == ' ') // if the user inputs spaces between the elements we are going to skip it
    {
        continue;
    }

    if(isDigit(exp[i])) // if our element of the string is diget put in the output
    {
        output += exp[i];
    }
    else if(exp[i] == '(') //if our element of the string is opening parenthesis put it in the operator stack
    {
        oper.push('(');
    }
    else if(exp[i] == ')') //if its closing parenthesis keep poping whats between the parenthsis in operator stack and put them in the output string
    {
        while(oper.top() != '(')
        {
            output += oper.top();
            oper.pop();
        }
        oper.pop(); //remove the opening parenthesis from the operator stack
    }
    else
    {                           
        while(!oper.empty() && priority(exp[i]) <= priority(oper.top())) /*while the expression is smaller or equal than the top operator in the stack, pop the smaller or the equal */             {                           /* operators from the stack and put them in the output string, then add the new operator to the stack*/
            output += oper.top();               /* if the stack is empty dont get in the while loop, and add the new operator*/
            oper.pop();
        }
        oper.push(exp[i]);  
    }
}
while(!oper.empty()) //if there exist any more operators in the stack operators, add them to the output string, and pop them from the stack;
{
    output += oper.top();
    oper.pop();
}
return output;

} // infix_to_postfix

 double postfix_evaluate(string exp)
 {
    stack<double> vals;

for(int i = 0; i < exp.length(); i++) // a loop that checks all the string elements(postfix string)
{
    if(isDigit(exp[i])) //if its digit push it in the stack vals
    {

        vals.push(exp[i] - '0'); // convert from ascii to real usable number (2) 0 = 48, 2 = 50, 2 = 50 - 48 = 2
    }
    else
    {
        double op2 = vals.top(); // get the operand 2
        vals.pop(); // remove it from the stack;
        double op1 = vals.top(); //get operand 1
        vals.pop();

        double result = mathOperate(op1, op2, exp[i]); // calculate the result using the function mathoperate
        vals.push(result);//push the result into the stack          
    }
}

return vals.top();

} // postfix_evaluate

 int main()
 {

string infixExp; // The infix expression we want to convert to postfix
cout << "Enter the expression you want to calculate: "<< endl;
cin >> infixExp;
cout << infix_to_postfix(infixExp) << endl;
string post_eva = infix_to_postfix(infixExp);

cout << postfix_evaluate(post_eva);

return 0;

} // main

...