I need your help in RBN in stack with class my code:
int calculator::compute()
{
for(i=0;i<8;i++){
if ((expr[i]=='+')||(expr[i]=='-')||(expr[i]=='*')||(expr[i]=='/'))
{x.pop();
switch (expr[i]) {
case'+':
x.push(expr[i-2]+expr[i-1]);
break;
case'-':
x.push(expr[i]-expr[i-1]);
break;
case'*':
x.push(expr[i-2]*expr[i-1]);
break;
case'/':
x.push(expr[i]/ expr[i-1]);
break; }
}
else
{
x.push(expr[i]);
x.top();
cout<<"|"<<x.top()<<"|"<<endl;
x.pop();}
}}
but it's giving me
int calculator::compute()
{
for(i=0;i<8;i++){
if ((expr[i]=='+')||(expr[i]=='-')||(expr[i]=='*')||(expr[i]=='/'))
{x.pop();
switch (expr[i]) {
case'+':
x.push(expr[i-2]+expr[i-1]);
break;
case'-':
x.push(expr[i]-expr[i-1]);
break;
case'*':
x.push(expr[i-2]*expr[i-1]);
break;
case'/':
x.push(expr[i]/ expr[i-1]);
break; }
}
else
{
x.push(expr[i]);
x.top();
cout<<"|"<<x.top()<<"|"<<endl;
x.pop();}
so i did 3 files: one is for the funktion and constructor of class:
#include<iostream>
#include<stack>
#include<string>
#include"class1.h"
using namespace std;
calculator::calculator(string f,stack<int> n)
{expr=f;
x=n;}
int calculator::compute()
{
for(i=0;i<8;i++){
if ((expr[i]=='+')||(expr[i]=='-')||(expr[i]=='*')||(expr[i]=='/'))
{
switch (expr[i]) {
case'+':
expr[i-2]+expr[i-1];
x.top();
x.pop();
break;
case'-':
x.push(expr[i-1]-expr[i-2]);
break;
case'*':
x.push(expr[i-2]*expr[i-1]);
break;
case'/':
x.push(expr[i-1]/ expr[i-2]);
break; }
}
else
{
x.push(expr[i]);
x.top();
cout<<"|"<<x.top()<<"|"<<endl;
x.pop();}
}}
and one for main:
#include<iostream>
#include<stack>
#include<string>
#include"class1.h"
using namespace std;
int main()
{
stack<int> n;
string d="812+4*+";
calculator calc(d,n);
calc.compute();
return 0;
}
and one for the class:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class calculator{
private:
int i;
stack<int>x;
string expr;
public:
calculator(string,stack<int>);
int compute();
};
i don't know where the problem is :(
The issue with the code giving incorrect output - this line return x.top(); is inside the for-loop, so the loop will execute only once.
kais2 wrote:
The program should give me the result of every operation
|1| |3| |4| |12| |20|
|2| |8| |3| |8|
|8| |8|
To achieve that, take line 46 and move it.
cout<<"|"<<x.top()<<"|"<<endl;
It is currently inside the last part of the if-else statement. It needs to be exactly where you currently have the return x.top(); at line 48, and the latter needs to be moved to line 49.5 - that is to say, between the two closing braces at line }}.
something like this: