4.已知运算式判断合法性及求值

ゞ 浴缸里的玫瑰 2022-06-02 09:58 245阅读 0赞





















成绩 10 开启时间 2017年11月24日 星期五 00:00
折扣 0.8 折扣时间 2017年12月18日 星期一 00:00
允许迟交 关闭时间 2017年12月31日 星期日 00:00

题目:给定后缀表达式,计算出该式的值。为简单起见,用于计算的数字均在0-9之间。

输入:

某个四则运算式的后缀表达式,其中除法”/“简化为整除。

输出:

该四则运算式的计算结果。若后缀表达式不合法,输出“ERROR!”;若计算过程中有除以0的情况,输出”DIV0!”






















  测试输入关于“测试输入”的帮助 期待的输出关于“期待的输出”的帮助 时间限制关于“时间限制”的帮助 内存限制关于“内存限制”的帮助 额外进程关于“{$a} 个额外进程”的帮助
测试用例 1 以文本方式显示


  1. 11+↵


以文本方式显示


  1. 2↵


1秒 64M 0
  1. #include<cstdio>
  2. #include<string>
  3. #include<map>
  4. #include<stack>
  5. #include<math.h>
  6. #include<iostream>
  7. using namespace std;
  8. stack<char> Op;
  9. stack<int> Opnum;
  10. string Instruction;
  11. int GetproiIncoming(char c)
  12. {
  13. switch (c)
  14. {
  15. case('+') : return 3;
  16. case('-') : return 3;
  17. case('*') : return 5;
  18. case('/') : return 5;
  19. //case('%') : return 5;
  20. //case('(') : return 10;
  21. //case('^') : return 8;
  22. }
  23. }
  24. int GetproInstack(char c)
  25. {
  26. switch (c)
  27. {
  28. case('+') : return 4;
  29. case('-') : return 4;
  30. case('*') : return 6;
  31. case('/') : return 6;
  32. //case('%') : return 6;
  33. //case('(') : return 1;
  34. //case('^') : return 7;
  35. }
  36. }
  37. int Comput(char c, int a, int b)
  38. {
  39. switch (c)
  40. {
  41. case('+') : return a + b;
  42. case('-') : return a - b;
  43. case('*') : return a*b;
  44. case('/') : return a / b;
  45. //case('%') : return a%b;
  46. //case('^') : return (int)pow(double(a), double(b));
  47. }
  48. }
  49. void getresult(string Instruction)
  50. {
  51. for (int i = 0; Instruction[i]; i++)
  52. {
  53. if (Instruction[i] >= '0'&&Instruction[i] <= '9')
  54. {
  55. int num = Instruction[i] - '0';
  56. Opnum.push(num);
  57. }
  58. else
  59. {
  60. if (Opnum.size() < 2)
  61. {
  62. printf("ERROR!\n");
  63. return;
  64. }
  65. else
  66. {
  67. int a = Opnum.top(); Opnum.pop();
  68. int b = Opnum.top(); Opnum.pop();
  69. if (Instruction[i] == '/'&&a == 0)
  70. {
  71. printf("DIV0!\n");
  72. return;
  73. }
  74. int num = Comput(Instruction[i], b, a);
  75. Opnum.push(num);
  76. }
  77. }
  78. }
  79. if (Opnum.size() > 1)
  80. {
  81. printf("ERROR!\n");
  82. return;
  83. }
  84. printf("%d\n",Opnum.top());
  85. }
  86. int main()
  87. {
  88. getline(cin, Instruction);
  89. getresult(Instruction);
  90. return 0;
  91. }

发表评论

表情:
评论列表 (有 0 条评论,245人围观)

还没有评论,来说两句吧...

相关阅读

    相关 二叉树遍历序列

    二叉树,我们能够了解,已知二叉树后序遍历序列和中序遍历序列,或者是前序遍历序列与中序遍历序列,可以唯一确定一棵树; 例 1:已知二叉树后序遍历序列是bfegcda,中序遍历序

    相关 判断输入框字符合法性

    在整体保存的时候判断输入框的合法性,当有大量输入框的时候,既浪费时间,有及其容易出错,昨天就搞了一个多小时,才发现居然是因为在js函数中将英文的”;”写成了中文的”;”。哎,j