文字列の形式の単純な方程式がある場合、最も実用的な方法は、文字列をprefix
orpostfix
表記に解析し、それに応じて評価することです...
infix
元の文字列が(基本的な数学を学ぶために人間が使用する表記法)であると仮定すると...
1000 * (200+3928)/2333
次に、それを変換しpostfix
て取得します...
1000, 200, 3928, +, *, 2333, /
この表記法を使用すると、コンピューターは単純なループとスタックを使用して式を簡単に評価できます...
楽しい部分はあなたに任せたいので、実際のコードは投稿しませんが、疑似コードで有利なスタートを切りたい場合は、ここに...
infix to postfix :
create empty array `postfix` and `temp`
split the expression up into an array `A` by each operand/operator
foreach token in `A`:
if char is operand :
push to postfix stack
if char is open parenthesis:
push to temp stack
if char is close parenthesis:
while top of temp stack != '(' :
push top of temp stack to postfix stack
pop top of temp stack
end while
pop top of temp stack
if char is operator:
while temp stack isn't empty *and* top of temp stack != '(' *and* precendence(char) <= precendence(top of temp stack) :
push top of temp stack to postfix stack
pop top of temp stack
end while
push char to temp stack
end for loop
while temp stack is not empty
push top of temp stack to postfix stack
pop top of temp stack
end while
return postfix stack (will be your postfix stack to evaluate)
evaluate postfix stack:
create array A
foreach token in postfix stack:
if char is operand:
push to A stack
if char is operator:
int x = pop A stack
int y = pop A stack
result = x (operation) y
push result to A stack
end for loop
return top of A stack (this will be the final result)