duanhuo7441 2010-11-21 05:42
浏览 19
已采纳

如何分析代数表达式

I am going to make a program that can analyse a algebraic expression.
For example:
<?php echo cal ('5*5+2*2'); ?>
My program will know that it will multiply 5 with 5 and 2 with 2 first, then plus them. I want to analyse it myself, not by php.

  • 写回答

2条回答 默认 最新

  • duanjiu3486 2010-11-21 06:04
    关注

    You can take the 'infix' expression and using a stack, turn it into a 'prefix' or 'postfix' expression to decide order of operation (Parenthesis, Exponentiation, Multiplication or Division, Addition or Subtraction).

    For example the expression ([5][ * ][5][ + ][2][ * ][2]) would be transformed into the postfix expression [5][5][ * ][2][2][ * ][ + ]. this 'postfix' expression can now be read as 'five and five multiplied, two and two multiplied, and then added together' which would preserve the order of operation.

    Another way to think of the 'prefix/postfix' idea is that of multiple stacks. When you encounter the number 5, push it onto the primary stack. When you encounter the multiply symbol, store it in the secondary stack. When you get to the next 5, push it onto the primary stack, then pop all of the items off of your secondary stack and push them onto your primary stack.

    Once you have the operators and operands in correct order, it's a matter of popping the items off the stack and then evaluating them.

    I remember figuring out this problem in my Computer Science 102 course in college. Are you doing this for fun, or just trying to figure it out?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退