I'm trying to write a calculator code to evaluate addition, subtraction, and squares. For example, the expression "1000 6^ - 5^ 1;" should evaluate to 1012. For some reason my code gives me the wrong answer :( It evaluates to 63. Where does the issue occur in my code?
#include <iostream>
using namespace std;
int main()
{
int answer = 0, num;
char sign;
cin >> num;
while (cin >> sign)
{
if (sign == '^')
{
answer = num * num;
cin >> sign >> num;
if (sign == ' ')
{
answer = num;
}
else if (sign == '-')
{
answer -= num;
}
}
else
{
if (sign == ' ')
{
cin >> num;
answer = num;
}
else if (sign == '-')
{
cin >> num;
answer -= num;
}
}
}
cout << answer << endl;
return 0;
}
CodePudding user response:
Let's take a step-by-step approach. Taking the input as 1000 6^ - 5^ 1;
, which is actually 1000<spacebar> <spacebar>6^<spacebar>-<spacebar>5^<spacebar> <spacebar>1;
Firstly, after you take 1000 as num,
<spacebar>
follow as asign
. As<spacebar>
does not match any of thesign
, this1000
is discarded because it does not hit any of theif
case.Then,
sign
, making<spacebar>6 -> 6
asnum
, sonum
becomes the6
. Then,^
is encountered. That adds36
to theanswer
, making theanswer
to42
.Then again
<spacebar>
is encountered, making theanswer
untouched. Then,-
sign
is encountered. reading<spacebar>5 -> 5
asnum
, it will subtract5
from42
, making theanswer
37
.Next,
^
will be encountered, adding25
to theanswer
, theanswer
will be62
.Then,
<spacebar>
is again encountered as asign
, having no effect to theanswer
.Lastly,
<spacebar>1 -> 1
to theanswer
, Therefore, the finalanswer
will be63
for this expression. Additional;
will be treated as asign
with no matches, therefore will not affect the finalanswer
.
As you see, because of the <spacebar>
and the fact that cin >> <char>
only takes exactly 1 character as the input, you get unexpected result.
Remember: Computer exactly does what you programmed, not what you actually intended.
If you want to parse the mathematical expression correctly, study about
Shunting-yard algorithm, https://en.wikipedia.org/wiki/Shunting-yard_algorithm
And Postfix notation. https://en.wikipedia.org/wiki/Reverse_Polish_notation
Those two algorithms are extensively used when the real-world calculator is implemented.
CodePudding user response:
I am not an expert but this type of problem (calculator) requires usage of stack, because there are many things to consider like operator precedence. For example, if there is a bracket then expression within brackets should be solved first. So, I advise to look in this further as there will be many good article explaining this.
CodePudding user response:
your current structure is wrong! and u need to add fist number to answer at beginning
try this struct:
|- while loop
|- take sign & num
|
check operator ^ is present after that
|
if present -> answer (sign)= num * num
|
else -> answer (sign)= num