Calculator help

Hi.
I am making a calculator. I can now do +, -, / and *. Pretty simple. The user has to type for example 1+1 or 2-1 and then gets the answer. I now want to add an option to add, subtract or multiply more numbers at the same time, like 1+1+1, but at the same time be able to add just 2 numbers or 4 if the user want's. How can I do this? :)
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
#include <iostream>
#include <math.h>

using namespace std;

long double num1, num2, num3, result;
char op;

int main()
{
cout << "CALCULATOR\nBy Anonymous";
while(true){
cout << "\n\nPlease enter your problem: ";
cin >> num1 >> op >> num2;

switch(op)
    {
    case '+':
        result = num1 + num2;
        break;
    case '-':
        result = num1 - num2;
        break;
    case '*':
        result = num1 * num2;
        break;
    case '/':
        result = num1 / num2;
        break;
    }


    cout << num1 << op << num2 << "=" << result;
}
}
There are answers to this problem all over the place, but if you want to try and figure it out for yourself...

1. start off by working out how to deal with an arbitrary long (within limits) list of numbers.

2. work out how to deal with operators as well as the values (operands)

3. then add basic maths (treat all operators as equal precedence)

4. modify the code to deal with operator precedence.

There are pretty straightforward solutions to these problems, but the fun is in solving it yourself!!

I will say that the most basic solution involves arrays. And that understanding how cin reports errors would be useful (so you can spot when you have an operator when you expect a number.)

Andy
Last edited on
Topic archived. No new replies allowed.