Im trying to make a basic calculator that takes in an expression. Im not really sure where im going wrong so if someone could please take a look at my code and give a few suggestions.
Without looking too hard at your code, I think the main problem is that you're not taking precedence into consideration when pushing operators into your stack. Regardless of the particular operators in an expression, the program will always apply them in the same order. The end result being that 1+2*3 ≠ 2*3+1.
Another subtlety is that ^ typically associates to the right. Meaning a^b^c == a^(b^c).
I was just trying to get it to do a basic expression first like (3+4) but it wasnt working so i decided to comment all of that out until i figured out the rest. I have found out that i need to convert my exp to double using strtod().
It will be better to use if else loop then switch case. Your code makes confused. I do not have a mean "precedence" ?
really it is so confusing.. Change the codes...
switch(operators.top()){
case '+':
numbers.push(num1+num2);
break;
case '-':
numbers.push(num1-num2);
break;
case '*':
numbers.push(num1*num2);
break;
case '/':
numbers.push(num1/num2);
break;
case '^':
numbers.push(pow(num1,num2));
break;
case '%':
numbers.push(fmod(num1,num2));
break;
case '~':
numbers.push(num2 * -1);
break;
}
@Jackson Marie - It's not good practice to have >1 return expression. Much better to declare a return variable of the correct type and set that in your code. Neither will your variables compare if you have spaces:
1 2
char b = 'b';
if (b == ' b ')
the above will evaluate to false not true as you expect.