Calculator output

Hello, (this calculator without operator precedence) the problem is that i want this calculator to output
1+2*3/4=2.25
However, now it output
1+2*3/4=
2.25


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
	double first_number, another_number;
	char action;
	bool sentry = true;

	cin >> first_number;

	while (sentry)
	{
		cin >> action;

		if (action == '=')
		{
			cout << first_number<<endl;
			sentry = false;
			break;
		}
		else {
			cin >> another_number;

			switch (action)
			{
				case '+': first_number = first_number + another_number;
					break;
				case '-': first_number = first_number - another_number;
					break;
				case '*': first_number = first_number * another_number;
					break;
				case '/': first_number = first_number / another_number;
					break;
			}
		}
	}
    return 0;
}
Last edited on
it is doing what you told it.
you told it to compute
1+2 (3)
* 3 (9)
/ 4 (2.25)

this is caused by ignoring operator precedence.

The usual way to do this is to use a stack and reverse polish logic. If its a value, push onto the stack, if its an operator, pop the stack twice, do that operation, push result back on the stack. You have to re-order the string into reverse polish first though, which is done with a tree traversal or you can do it with messy logic.

looks like
2,3,* (6)
6,4,/ (1.5)
1.5,1,+ (2.5)
done, 2.5
Topic archived. No new replies allowed.