I'm doing an advanced calculation process (something similar to scientific mode for calculator). I'm seeking for algorithm that can help me finish this task for my project. Here is the problem:

Let take an example 10+10*2. The result of this SHOULD be 30. So, the problem I'm facing is that divide and multiply should take advantage of + and - operation (even without brackets). I basically know how to do a calculator which have basic functions like result of 10+10*2 is 40 (put first number in variable, then second in another variable, and third in first variable again). In regard, I wrote a few algo but none of them worked. My solution to this would be to parse whole strng '10+10*2' and then split them apart to detect operations +, -, / and *. Then recalculate the process. But that seems a bit longer and I suspect a lot of "if" conditions plus who use a string while calculating?

We can discuss about any idea.
Thanks!

P.S. I'm familiar with a few languages so any solution can be made. I accept pseudo codes in various high-level languages. I'm just not familiar with algo (programming logic).

有帮助吗?

解决方案

The most easiest solution for your example is to cycle through your expression twice.

In first run, you only multiply/divide, you dont add or substract anything. In second run, there is no multiplying/dividing, therefore you can do it form left to right.

Pseudocode :

for (number : numbers) { //for each number in numbers in your expression
  if (next operator is */){
    number */= nextNumber();
    removeNextOperator();
    removeNextNumber();
    doNotMoveFromThisNumberInNextStep(); //like decrementing index variable in classic for-cycle
  }
}

now we have expression with only +-, which you say you know how to do it


I thought a bit and it can be done in one run! You only need to remember the sum you get from adding/substracting when you find */.

Pseudocode :

int sum = 0;
for (number : numbers) { //for each number in numbers in your expression
  if (next operator is */){
    number */= nextNumber();
    removeNextOperator();
    removeNextNumber();
    doNotMoveFromThisNumberInNextStep(); //like decrementing index variable in classic for-cycle
  } else { //next operator is +- or the last number
    sum +-= numberBefore() +- number;
  }
}

其他提示

You need to implement operation priority and you have only two category [+-] [*/] (however the common algorithm is the same):

  1. Split expression to numbers and operations
  2. Take the highest priority operation here is * / from left to right
  3. Calculate it and
  4. Replace the operation and numbers with the result and do 2

And yes, a lot of languages supports eval(arithmetic expression)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top