Salve, ho fatto un programmino che dovrebbe risolvere una banale espressione usando lo stack ma una volta inserita l'espressione mi da risultato sempre 6 , perchè???
https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-prn2/v/t35.0-12/10287603_4180198519919_838562371_o.jpg?oh=1ccb0f6985211372f08825c7e325dead&oe=535FE882&__gda__=1398778984_61afbbea6a962bca4196f0c0ceba6b73
il codice è:
expression.h
#include <iostream>
#include <stack>
using namespace std;
double insertExpr(istream& ins);
void calculateExpr(stack<double> &numbers, stack<char> &operations);
arithexpression.cpp
#include "expression.h"
#include <iostream>
#include <cstdlib>
#include <stack>
#include <cctype>
#include <cstring>
using namespace std;
double insertExpr(istream& ins)
{
stack<char> operations;
stack<double> numbers;
double number;
char operation;
while(ins && ins.peek()!='\n')
{
if(isdigit(ins.peek()) || ins.peek()=='.')
{
ins>>number;
numbers.push(number);
}
else if(strchr("+-*/",ins.peek())!=NULL)
{
ins>>operation;
operations.push(operation);
}
else if(ins.peek()==')')
{
ins.ignore();
calculateExpr(numbers,operations);
}
else if(ins.peek()=='(' || ins.peek()==' ')
ins.ignore();
}
return numbers.top();
}
void calculateExpr(stack<double> &numbers, stack<char> &operations)
{
double operand1, operand2;
operand2=numbers.top(); //si trova prima il secondo operando
numbers.pop();
operand1=numbers.top(); //poi il primo
numbers.pop();
switch(operations.top())
{
case '+': numbers.push(operand1+operand2);
break;
case '-': numbers.push(operand1-operand2);
break;
case '*': numbers.push(operand1*operand2);
break;
case '/': numbers.push(operand1/operand2);
break;
}
operations.pop();
}
expression.cpp
#include "expression.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
double risultato;
cout<<"Espressione:\n";
risultato=insertExpr(cin);
cout<<"Risultato: "<<risultato<<"\n";
return 0;
}