Calculator

Is there a way to write a program in such a way as to allow the user to type in the equation themselves? Similar to a graphing calculator. Example the user could type in 9*4 and press enter to receive the answer 36.
Yes. Off the top of my head, you could just make three variables for a 2 number equation (i.e 2+4). It could look something like 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
int num1; //This could be a double or float if you are dealing with decimals
char operator; //The data type char can hold symbols, like +. -, *, /
int num2; //the second number, could also be a float/double

using namespace std;

int main{
 // Optional prompt for user to enter in equation

cin>>num1>>operator>>num2 //Equation is entered in

switch (operator)

case '+' :
cout<<num1*num2;
break;

case '-' :

cout<<num1-num2;
break;

// ... And so on for all of the possible operators (/, *, etc)


}


You could also use this for functions (i.e. num1^num2 = pow(num1, num2))
Of course.

It's more usual practice to read the whole string in and then split it up (tokenize it). To start with, this makes error handling easier. Then you can deal a bigger range of formatting styles (e.g. 1 + 2 versus 1+2). And it's easier to deal wth more complicated expressions, like 1 - 2 + 3 - 4 + 5 + 6

It's not too difficult to deal with arithmatic, including brackets, in this way. After reading the string in, you have to walk it char by char to find the numbers and operators are.

Handling just + and - is pretty easy.

You check each char in turn and if you find a digit, add it to a number string (which starts of empty).
- if it's anything else, add the existing number string to your list of tokens and clear the string.
- - if it's a space, ignore it
- - if it's an operator, add it to your list of tokens.
Anything else in the string is an error and you should abort.

Once you've finished tokenizing, calculate the results.

Adding multiplication and division, and brackets, is that bit harder (involves stacks).

Andy

Last edited on
Thanks!
Topic archived. No new replies allowed.