| David Goldman (5) | |
| 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. | |
|
|
|
| MildewyTester (51) | |||
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:
You could also use this for functions (i.e. num1^num2 = pow(num1, num2)) | |||
|
|
|||
| andywestken (1950) | |
|
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
|
|
| David Goldman (5) | |
| Thanks! | |
|
|
|