表达式求值

[问题描述]

一个算术表达式是由操作数(operand)、运算符(operator)和界限符(delimiter)组成的。假设操作数是正整数,运算符只含加减乘除等四种运算符,界限符有左右括号和表达式起始、结束符“#”,如:#(7+15)*(23-28/4)#。引入表达式起始、结束符是为了方便。编程利用“算符优先法”求算术表达式的值。

[基本要求]

(1) 从键盘读入一个合法的算术表达式,输出正确的结果。

(2) 显示输入序列和栈的变化过程。

[选作内容]

(1) 扩充运算符集合。

(2) 引入变量操作数。

(3) 操作数类型扩充到实数。

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. #include <conio.h>
  6.  
  7. #define TRUE 1
  8. #define FALSE 0
  9. #define Stack_Size 50
  10.  
  11. char ops[7]={'+','-','*','/','(',')','#'}; /*运算符数组*/
  12.  
  13. int cmp[7][7]={{2,2,1,1,1,2,2}, /*用来进行比较运算符优先级的矩阵,3代表'=',2代表'>',1代表'<',0代表不可比*/
  14. {2,2,1,1,1,2,2},
  15. {2,2,2,2,1,2,2},
  16. {2,2,2,2,1,2,2},
  17. {1,1,1,1,1,3,0},
  18. {2,2,2,2,0,2,2},
  19. {1,1,1,1,1,0,3}};
  20.  
  21. typedef struct
  22. {
  23. char elem[Stack_Size];
  24. int top;
  25. }SeqStack; /*运算符栈的定义*/
  26.  
  27. typedef struct
  28. {
  29. int elem[Stack_Size];
  30. int top;
  31. }nSeqStack; /* 运算数栈的定义*/
  32.  
  33. void InitStack(SeqStack *S) /*初始化运算符栈*/
  34. {
  35. S->top =-1;
  36. }
  37.  
  38. void InitStackn(nSeqStack *S) /*初始化运算数栈*/
  39. {
  40. S->top =-1;
  41. }
  42.  
  43. int IsEmpty(SeqStack *S) /*判断栈S为空栈时返回值为真,反之为假*/
  44. {
  45. return(S->top==-1?TRUE:FALSE);
  46. }
  47.  
  48. int IsEmptyn(nSeqStack *S) /*判断栈S为空栈时返回值为真,反之为假*/
  49. {
  50. return(S->top==-1?TRUE:FALSE);
  51. }
  52.  
  53. /*判栈满*/
  54. int IsFull(SeqStack *S) /*判断栈S为满栈时返回值为真,反之为假*/
  55. {
  56. return(S->top==Stack_Size-1?TRUE:FALSE);
  57. }
  58.  
  59. int IsFulln(nSeqStack *S) /*判断栈S为满栈时返回值为真,反之为假*/
  60. {
  61. return(S->top==Stack_Size-1?TRUE:FALSE);
  62. }
  63.  
  64. int Push(SeqStack *S, char x) /*运算符栈入栈函数*/
  65. {
  66. if (S->top==Stack_Size-1)
  67. {
  68. printf("Stack is full!\n");
  69. return FALSE;
  70. }
  71. else
  72. {
  73. S->top++;
  74. S->elem[S->top]=x;
  75. return TRUE;
  76. }
  77. }
  78.  
  79. int Pushn(nSeqStack *S, int x) /*运算数栈入栈函数*/
  80. {
  81. if (S->top==Stack_Size-1)
  82. {
  83. printf("Stack is full!\n");
  84. return FALSE;
  85. }
  86. else
  87. {
  88. S->top++;
  89. S->elem[S->top]=x;
  90. return TRUE;
  91. }
  92. }
  93.  
  94. int Pop(SeqStack *S, char *x) /*运算符栈出栈函数*/
  95. {
  96. if (S->top==-1)
  97. {
  98. printf("运算符栈空!\n");
  99. return FALSE;
  100. }
  101. else
  102. {
  103. *x=S->elem[S->top];
  104. S->top--;
  105. return TRUE;
  106. }
  107. }
  108.  
  109. int Popn(nSeqStack *S, int *x) /*运算数栈出栈函数*/
  110. {
  111. if (S->top==-1)
  112. {
  113. printf("运算符栈空!\n");
  114. return FALSE;
  115. }
  116. else
  117. {
  118. *x=S->elem[S->top];
  119. S->top--;
  120. return TRUE;
  121. }
  122. }
  123.  
  124. char GetTop(SeqStack *S) /*运算符栈取栈顶元素函数*/
  125. {
  126. if (S->top ==-1)
  127. {
  128. printf("运算符栈为空!\n");
  129. return FALSE;
  130. }
  131. else
  132. {
  133. return (S->elem[S->top]);
  134. }
  135. }
  136.  
  137. int GetTopn(nSeqStack *S) /*运算数栈取栈顶元素函数*/
  138. {
  139. if (S->top ==-1)
  140. {
  141. printf("运算符栈为空!\n");
  142. return FALSE;
  143. }
  144. else
  145. {
  146. return (S->elem[S->top]);
  147. }
  148. }
  149.  
  150. int Isoperator(char ch) /*判断输入字符是否为运算符函数,是返回TRUE,不是返回FALSE*/
  151. {
  152. int i;
  153. for (i=0;i<7;i++)
  154. {
  155. if(ch==ops[i])
  156. return TRUE;
  157. }
  158. return FALSE;
  159. }
  160.  
  161. /*
  162. int isvariable(char ch)
  163. { if (ch>='a'&&ch<='z')
  164. return true;
  165. else
  166. return false;
  167. }*/
  168.  
  169. char Compare(char ch1, char ch2) /*比较运算符优先级函数*/
  170. {
  171. int i,m,n;
  172. char pri;
  173. int priority;
  174. for(i=0;i<7;i++) /*找到相比较的两个运算符在比较矩阵里的相对位置*/
  175. {
  176. if(ch1==ops[i])
  177. m=i;
  178. if (ch2==ops[i])
  179. n=i;
  180. }
  181.  
  182. priority = cmp[m][n];
  183. switch(priority)
  184. {
  185. case 1:
  186. pri='<';
  187. break;
  188. case 2:
  189. pri='>';
  190. break;
  191. case 3:
  192. pri='=';
  193. break;
  194. case 0:
  195. pri='$';
  196. printf("表达式错误!\n");
  197. break;
  198. }
  199. return pri;
  200. }
  201.  
  202. int Execute(int a, char op, int b) /*运算函数*/
  203. {
  204. int result;
  205. switch(op)
  206. {
  207. case '+':
  208. result=a+b;
  209. break;
  210. case '-':
  211. result=a-b;
  212. break;
  213. case '*':
  214. result=a*b;
  215. break;
  216. case '/':
  217. result=a/b;
  218. break;
  219. }
  220. return result;
  221. }
  222.  
  223. int ExpEvaluation()
  224. /*读入一个简单算术表达式并计算其值。optr和operand分别为运算符栈和运算数栈,OPS为运算符集合*/
  225. {
  226. int a,b,v,temp;
  227. char ch,op;
  228. char *str;
  229. int i=0;
  230.  
  231. SeqStack optr;
  232. nSeqStack operand;
  233.  
  234. InitStack(&optr);
  235. InitStackn(&operand);
  236. Push(&optr,'#');
  237. printf("请输入表达式(以#结束):\n"); /*表达式输入*/
  238. str =(char *)malloc(50*sizeof(char));
  239. gets(str);
  240.  
  241. ch=str[i];
  242. i++;
  243. while(ch!='#'||GetTop(&optr)!='#')
  244. {
  245. if(!Isoperator(ch))
  246. {
  247. temp=ch-'0'; /*将字符转换为十进制数*/
  248. ch=str[i];
  249. i++;
  250. while(!Isoperator(ch))
  251. {
  252. temp=temp*10 + ch-'0'; /*将逐个读入运算数的各位转化为十进制数*/
  253. ch=str[i];
  254. i++;
  255. }
  256. Pushn(&operand,temp);
  257. }
  258. else
  259. {
  260. switch(Compare(GetTop(&optr),ch))
  261. {
  262. case '<':
  263. Push(&optr,ch);
  264. ch=str[i];
  265. i++;
  266. break;
  267. case '=':
  268. Pop(&optr,&op);
  269. ch=str[i];
  270. i++;
  271. break;
  272. case '>':
  273. Pop(&optr,&op);
  274. Popn(&operand,&b);
  275. Popn(&operand,&a);
  276. v=Execute(a,op,b); /* 对a和b进行op运算 */
  277. Pushn(&operand,v);
  278. break;
  279. }
  280. }
  281. }
  282. v=GetTopn(&operand);
  283. return v;
  284. }
  285.  
  286. void main() /*主函数*/
  287. {
  288. int result;
  289. result=ExpEvaluation();
  290. printf("\n表达式结果是%d\n",result);
  291. }

下面这个是在网上找的:

  1. C++ 实现的加、减、乘、除表达式计算
  2.  
  3. 前些日子面试一个开发工作,考官出了这么一笔试题目,要我写出实现过程, 思量半天,终于
  4. C++ 完成,现将代码贴出,与诸同道共分享。
  5.  
  6. // 头文件 Calc.h
  7. #ifndef __CALC_H__
  8. #define __CALC_H__
  9. #include <stack>
  10. #define ascii_int(x) (x >= 0x30 && x <= 0x39) ? (x - 0x30) : (x)
  11. const int GREATER = 1;
  12. const int EQUAL = 0;
  13. const int LESS = -1;
  14. class Calculate {
  15. public:
  16. int evaluteExpr(char *exp);
  17. private:
  18. int getLevel(char ch);
  19. bool isOperator(char ch);
  20. int compareOpteratorLevel(char inputChar, char optrStackTop);
  21. int calc(int num1, int num2, char op);
  22. void evaluate(char ch);
  23. private:
  24. std::stack<int> _opnd_stack;
  25. std::stack<char> _optr_stack;
  26. static char _optr[];
  27. static int _level[];
  28. };
  29. #endif
  30.  
  31. // 头文件的实现代码 Calc.cxx
  32. #include "Calc.h"
  33. char Calculate::_optr[] = {'#', '(', '+', '-', '*', '/', ')'};
  34. int Calculate::_level[] = { 0, 1, 2, 2, 3, 3, 4 };
  35. // Get current operator level for calculating
  36. int Calculate::getLevel(char ch) {
  37. for (int i = 0; *(_optr+i) != '\0'; ++i)
  38. if (*(_optr+i) == ch)
  39. return *(_level+i);
  40. }
  41. // Calculate the operands
  42. int Calculate::calc(int num1, int num2, char op) {
  43. switch (op)
  44. {
  45. case '+':
  46. return num1 + num2;
  47. case '-':
  48. return num1 - num2;
  49. case '*':
  50. return num1 * num2;
  51. case '/':
  52. return num1 / num2;
  53. }
  54. }
  55. // judge inputing character is operator or not
  56. bool Calculate::isOperator(char ch) {
  57. for (char *p = _optr; *p != '\0'; ++p)
  58. if (*p == ch)
  59. return true;
  60. return false;
  61. }
  62. // Compare level of input operator and the top operator of operator stack
  63. int Calculate::compareOpteratorLevel(char inputChar, char optrStackTop) {
  64. // if (inputChar == '(' && optrStackTop == ')')
  65. // return EQUAL;
  66. // else
  67. if (inputChar == '(')
  68. return GREATER;
  69. if (inputChar == ')' && optrStackTop == '(')
  70. return EQUAL;
  71. else if (inputChar == ')')
  72. return LESS;
  73. if (inputChar == '#' && optrStackTop == '#')
  74. return EQUAL;
  75. // else if (inputChar == '#')
  76. // return LESS;
  77. return (getLevel(inputChar) > getLevel(optrStackTop)) ? GREATER : LESS;
  78. }
  79. // Evaluate value while inputing operators
  80. void Calculate::evaluate(char ch) {
  81. char op;
  82. int num, result;
  83. if (!isOperator(ch)) {
  84. _opnd_stack.push(ascii_int(ch));
  85. return ;
  86. }
  87. switch (compareOpteratorLevel(ch, _optr_stack.top()))
  88. {
  89. case GREATER :
  90. _optr_stack.push(ch);
  91. break;
  92. case EQUAL :
  93. _optr_stack.pop();
  94. break;
  95. case LESS :
  96. num = _opnd_stack.top();
  97. _opnd_stack.pop();
  98. result = _opnd_stack.top();
  99. _opnd_stack.pop();
  100. op = _optr_stack.top();
  101. _optr_stack.pop();
  102. result = calc(result, num, op);
  103. _opnd_stack.push(result);
  104. evaluate(ch);
  105. break;
  106. }
  107. }
  108. // Evaluate user specified expression
  109. int Calculate::evaluteExpr(char *exp) {
  110. _optr_stack.push('#');
  111. for (char *p =exp; *p != '\0'; ++p )
  112. evaluate(*p);
  113. int result = _opnd_stack.top();
  114. _opnd_stack.pop();
  115. return result;
  116. }
  117.  
  118. // 测试代码 calc_test.cxx
  119. #include <iostream>
  120. #include "Calc.h"
  121. using namespace std;
  122. int main(void) {
  123. Calculate *calc = new Calculate();
  124. cout << "1+3*(4+7) = "
  125. << calc->evaluteExpr("1+3*(4+7)#")
  126. << endl;
  127. cout << "((1+2)) = "
  128. << calc->evaluteExpr("((1+2))#")
  129. << endl;
  130. cout << "3*8+9/7-5-9+(1-9)/4 = "
  131. << calc->evaluteExpr("3*8+9/7-5-9+(1-9)/4#")
  132. << endl;
  133. cout << "(6-7)*(5+9) = "
  134. << calc->evaluteExpr("(6-7)*(5+9)#")
  135. << endl;
  136. cout << "0*8+0/6-9+(7-1) = "
  137. << calc->evaluteExpr("0*8+0/6-9+(7-1)#")
  138. << endl;
  139. delete calc;
  140. }
  141.  
  142. MinGW/G++ 3.4.5 编译如下:
  143. g++ -o test.exe Calc.cxx Calc_test.cxx
  144.  
  145. 作为一个演示算法够了, 但代码还是有一些缺点:
  146. (1) 只能处理一位数的加、减、乘、除表达式计算(可带括号)

c/c++ 表达式求值的更多相关文章

  1. 表达式求值(noip2015等价表达式)

    题目大意 给一个含字母a的表达式,求n个选项中表达式跟一开始那个等价的有哪些 做法 模拟一个多项式显然难以实现那么我们高兴的找一些素数代入表达式,再随便找一个素数做模表达式求值优先级表 - ( ) + ...

  2. 用Python3实现表达式求值

    一.题目描述 请用 python3 编写一个计算器的控制台程序,支持加减乘除.乘方.括号.小数点,运算符优先级为括号>乘方>乘除>加减,同级别运算按照从左向右的顺序计算. 二.输入描 ...

  3. 数据结构算法C语言实现(八)--- 3.2栈的应用举例:迷宫求解与表达式求值

    一.简介 迷宫求解:类似图的DFS.具体的算法思路可以参考书上的50.51页,不过书上只说了粗略的算法,实现起来还是有很多细节需要注意.大多数只是给了个抽象的名字,甚至参数类型,返回值也没说的很清楚, ...

  4. nyoj305_表达式求值

    表达式求值 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 Dr.Kong设计的机器人卡多掌握了加减法运算以后,最近又学会了一些简单的函数求值,比如,它知道函数min ...

  5. 利用栈实现算术表达式求值(Java语言描述)

    利用栈实现算术表达式求值(Java语言描述) 算术表达式求值是栈的典型应用,自己写栈,实现Java栈算术表达式求值,涉及栈,编译原理方面的知识.声明:部分代码参考自茫茫大海的专栏. 链栈的实现: pa ...

  6. 数据结构--栈的应用(表达式求值 nyoj 35)

    题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=35 题目: 表达式求值 时间限制:3000 ms | 内存限制:65535 KB描述 AC ...

  7. NOIP2013普及组 T2 表达式求值

    OJ地址:洛谷P1981 CODEVS 3292 正常写法是用栈 #include<iostream> #include<algorithm> #include<cmat ...

  8. HNU 12817 Shipura(表达式求值)

    题目链接:http://acm.hnu.cn/online/?action=problem&type=show&id=12817 解题报告:定义两种运算符号,一种是>>,就 ...

  9. NOIP201302表达式求值

    NOIP201302表达式求值 题目描述 Description 给定一个只包含加法和乘法的算术表达式,请你编程计算表达式的值. 输入描述 Input Description 输入仅有一行,为需要你计 ...

  10. OpenJudge计算概论-简单算术表达式求值

    /*===================================== 简单算术表达式求值 总时间限制: 1000ms 内存限制: 65536kB 描述 2位正整数的简单算术运算(只考虑整数运 ...

随机推荐

  1. RxJava操作符(08-条件和布尔操作)

    转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51671826 本文出自:[openXu的博客] 目录: All Amb Contains D ...

  2. Volley的基本使用

    Volley的基本使用 导入jar包 导入成功 源码 GET请求下载地址:http://download.csdn.net/detail/q4878802/9053969 POST请求下载地址:htt ...

  3. Android高级控件(六)——自定义ListView高仿一个QQ可拖拽列表的实现

    Android高级控件(六)--自定义ListView高仿一个QQ可拖拽列表的实现 我们做一些好友列表或者商品列表的时候,居多的需求可能就是需要列表拖拽了,而我们选择了ListView,也是因为使用L ...

  4. Servlet之异常处理

    当一个 Servlet 抛出一个异常时,Web 容器在使用了exception-type 元素的 web.xml 中搜索与抛出异常类型相匹配的配置. 前提是必须在 web.xml 中使用 error- ...

  5. spark idea 的配置问题

    不知道下面的错误是为什么? Error:scalac: missing or invalid dependency detected while loading class file 'RDD.cla ...

  6. EBS 客户表结构

     客户表/联系人/PARTY关联 HZ_PARTIES 客户账户表 HZ_CUST_ACCOUNTS SELECT hp.party_number --客户注册标识 , hp.party_name ...

  7. 【Unity Shaders】Lighting Models —— 光照模型之Lit Sphere

    本系列主要参考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同时会加上一点个人理解或拓展. 这里是本书所有的插图.这里是本书所需的代码和资源 ...

  8. Android 官方命令深入分析之android

    作者:宋志辉 android命令是一个非常重要的开发工具,它可以: 创建.删除和查看Android Virtual Devices(AVDs). 创建和更新android项目. 更新你的android ...

  9. CentOS配置

    1.在Vmware中安装好虚拟机. 2.客户机(即虚拟机中的centos)网络连接使用仅主机模式Host-only 3.在主机中网络配置上,配置IP地址 1.使用PieTTY远程连接该虚拟机 2.使用 ...

  10. 一台电脑上同启动两个Tomcat的方式,windows/Linux配置。

     安装两个jdk,一个JDK路径在:C:\ProgramFiles (x86)\Java\jdk1.7.0_25,另外一个JDK的路径在E:\UCMSServer\j2sdk 在环境变量里并设置J ...