Calculator: Chaining Of Operations

Pages: 12
I want to make a simple calculator which can read an expression and calculate it. Below I've posted the source code of my calculator program. It does the job but have some major problems-
1. The Result Shows Up Many Times and also shows my intermediate results which I dont want to show up at the screen.
2. It keeps the result saved after entering one expression and getting the result, which causes wrong result on calculating another expression in the same program run.
-------------------------------------------------------------------------------
What I Want It To Do:
1. Shows The Final Result For Each Expression.
2. Reset All Values and Program to Initial Stage After Getting Final Result.
NOTE: I'm a Beginner so try to make source code as simple as possible.

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 <iostream>
#include <cmath>
using namespace std;
//Simple Calculator By Chaining Of Operations
//res= result; lval=left value; rval=right value; op=operation symbol/code;
int main()
{
	cout<<"Please Enter An Expression\n";
	int lval,rval,res;
	cin>>lval;
	if(cin)
	for(char op;cin>>op;)
	{
		cin>>rval;
	if(op=='+')
		{
		res = lval+rval;
		lval = res;
		}
	if(op=='-')
		{
	        res = lval-rval;
	        lval = res;
		}
	if(op=='*')
		{
	        res = lval*rval;
	        lval = res;
		}
	if(op=='/')
    	        {
	        res = lval/rval;
	        lval = res;
		}
	else
		{
		cout<<"\nResult: "<<res;
    	        }
    
        } 
}
Last edited on
Please Help Me I'm Stuck :-(
closed account (48T7M4Gy)
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
42
43
44
45
#include <iostream>
#include <cmath>
using namespace std;
//Simple Calculator By Chaining Of Operations
//res= result; lval=left value; rval=right value; op=operation symbol/code;
int main()
{
    cout<<"Please Enter An Expression\n";
    int lval,rval,res;

//   if(cin)
//       for(char op; cin>>op;)
//       {

    char op = '\0';

    cin >> op;
    cin>>rval;
    cin>>lval;

    if(op == '+')
    {
        res = lval+rval;
        lval = res;
    }
    if(op=='-')
    {
        res = lval-rval;
        lval = res;
    }
    if(op=='*')
    {
        res = lval*rval;
        lval = res;
    }
    if(op=='/')
    {
        res = lval/rval;
        lval = res;
    }
    //          else
    //{
        cout<<"\nResult: "<<res;
    //}
}
I've corrected the mistake. It must have been something wrong with the for loop you used so I replaced it with a do loop instead. Also, at the end there was no need to put an else otherwise whenever you did a divide, it would crash. Finally, changing the variables from an integer to a double allows you to do calculations with decimal points.

Code:

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
42
#include <iostream>
#include <cmath>
using namespace std;
//Simple Calculator By Chaining Of Operations
//res= result; lval=left value; rval=right value; op=operation symbol/code;
int main()
{
	do {
		system("cls"); // clear the screen
		cout<<"Please Enter An Expression\n";
		double lval,rval,res;
		char op;
		cin>>lval;
		if(cin)
			cin>>op;
		if (cin)
			cin>>rval;
		cin.ignore(); // clear the input buffer
		if(op=='+')
		{
			res = lval+rval;
			lval = res;
		}
		else if(op=='-')
		{
			res = lval-rval;
			lval = res;
		}
		else if(op=='*')
		{
			res = lval*rval;
			lval = res;
		}
		else if(op=='/')
		{
			res = lval/rval;
			lval = res;
		}
		cout<<"\nResult: "<<res;
		cin.ignore(); // pause
	} while (true); // continue repeating
}
Thanks For Your Help But Now Things Got More Complicated LOL-
----------------------------------------------------------------------------------------------------
#Tom56785

I Forgot To tell you that my calculator was able to calculate any kind of expression such as 2+2, 2+5+5+9, 5+8/9 etc. What I'm Trying to say is it was able to perform calculation on any length of operation input.
----------------------------------------------------------------------------------------------------
#kemort

Your Code Returns Result as 0 when entered more than two values and operands. example 2+2+2
----------------------------------------------------------------------------------------------------
Please Guys Help Me
I Used For Loop To Continuosly Read The Entered Expression And Solve It. Try Running My Source Code with the following inputs:-
1. 5+5
2. 8+4+5
3. 5+5/2
4. 5+5+5+5+5
Alse Try To Enter Another Expression During The Same Run-
5+5+5
1+1+1
You'll Understand The Problem After Running The Program.
closed account (48T7M4Gy)
@Fateslayer. OK I didn't realise you were chaining the calculations.

That explains the (unusual) for statement.

A 'for' loop is not the best.

A while based on '=' being the terminator would be better and I'd suggest you use a switch structure to process the different op's.

The location of the cout will also determine whether you display just a final result or progressive results.

You might also be better off using double or float variables to avoid integer truncation when dividing numbers. :-)

PS I see that Tom has suggested most of this. My only other observation is 2+2+5/9 is an 'interesting' challenge.
Last edited on
I'm currently working on my code to do what you ask. It seems to be quite a challenge so far...
Can you post a source code please @kemort

thanks @Tom I appreciate it. Yeah it's a fun exercise for me Lol. stuck at it since a week.
don't worry about the math logic now just make it calculate normally such as left to right plain calculation. I'll try to add the Math Logic And Grammar later.
example 5+5*5=50 will be fine even though it's incorrect
5+5*5=30 I suppose by our usual rules
closed account (48T7M4Gy)
Yeah I'll keep you informed. Might take some time as it's midnight here. But I'll get back ASAP.

With the more complex challenges, leave those to another stage. The way it can be handled - i.e. brackets - is the intermediate calculations and operators are pushed onto a stack until a bracket is closed upon which the stack is pulled down. If that conveys anything.
@Kemort I'm thinking of using vectors. Will it be any good? thanks for your help man I appreciate it.
closed account (48T7M4Gy)
@ Fateslayer,

Everybody loves vectors for some reason and they would work. A simple array would work or even a std::stack

The challenge her is putting operators as well as numbers on the stack.

( Reverse polish calculators can do very complex calculations with 4 number registers! )
@kemort We can use two vectors for that BTW I got a question
reverse polish calculators requires user to input like this ~
5 5 + or 5+5 will work?

I just entered into a new region lol
infix to postfix conversion and using rpn
but I wanted to make a new calculator not to make something that already exists
closed account (48T7M4Gy)
@ Fateslayer,

RPN calculators do '5 push-up, 5, add'. The operator works on the bottom two registers and the answer is displayed and entered in the bottom register. A bracket is equivalent to a push, an operator brings the stack down (pop).

RPN is easier to implement. But you can get '5+5=' to work.
I'll see if I can come up with a solution for tomorrow since I don't have very much time to do it now anyway.
OK thank you both for helping me so much I hope we come up with a decent solution and hopefully a new one
After an hour or so of trying to come up with a solution to this issue you'll be glad to know I've finally found one! It took me a while but here's the code:

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cmath>
using namespace std;
//Simple Calculator By Chaining Of Operations
//res= result; lval=left value; rval=right value; op=operation symbol/code;

double calc(double, double, char);

int main() {
	do {
		system("cls"); // clear the screen
		cout << "Please Enter An Expression\n";
		double lval = NULL, rval = NULL, res = NULL;
		char op;
		//cin>>lval;
		//if(cin)
		//	cin>>op;
		//if (cin)
		//	cin>>rval;
		cin >> lval;
		do {
			op = NULL;
			rval = NULL;
			if (!cin.eof() && !cin.fail() && cin.peek() != '\n' && cin.peek() != '\0')
				cin >> op;
			else
				break;
			if (!cin.eof() && !cin.fail() && op != '\0' && cin.peek() != '\n' && cin.peek() != '\0')
				cin >> rval;
			else
				break;
			res = calc(lval, rval, op);
			lval = res;
		} while (!cin.fail() && !cin.eof());
		cin.clear();
		cin.ignore(INT_MAX, '\n'); // clear the input buffer
		cout << "\nResult: " << res;
		cin.ignore(); // pause
	} while (true); // continue repeating
}

double calc(double lval, double rval, char op) {
	double res;
	if (op=='+') {
		res = lval+rval;
		lval = res;
	} else if (op=='-') {
		res = lval-rval;
		lval = res;
	} else if (op=='*') {
		res = lval*rval;
		lval = res;
	} else if (op=='/') {
		res = lval/rval;
		lval = res;
	}
	return lval;
}


It sort of mutated...
Pages: 12