简单计算器
2015-11-04 21:19
253 查看
Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
Sample Output
这道题需要注意当当前符号为*/或*-时只能算前面的*/,+-千万不要算前面的+-,这样算有错,
注意最后一个是*/。
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
这道题需要注意当当前符号为*/或*-时只能算前面的*/,+-千万不要算前面的+-,这样算有错,
注意最后一个是*/。
#include <stdio.h> #include <string.h> const int maxn = 1005; char op[maxn], sign[maxn]; double val[maxn]; double oper ( double a, double b, char ch ) { switch ( ch ) //算运算符 { case '+' : return a+b; case '-' : return a-b; case '*' : return a*b; case '/' : return a*1.0/b; } } int priority ( char ch ) { if ( ch == '*' || ch == '/' ) //*/定义为2 return 2; if ( ch == '+' || ch == '-' ) //+-定义为1 return 1; return 0; } int main ( ) { int top, front; double ans; while ( gets ( op ) != '\0' && strcmp ( op, "0" ) != 0 ) { top = front = -1; int len = strlen ( op ); for ( int i = 0; i < len; i ++ ) { if ( op[i] == ' ' ) continue ; if ( op[i] >= '0' && op[i] <= '9' ) { int v = 0; //化成数字 while ( i < len && op[i] >= '0' && op[i] <= '9' ) v = v*10+( op[i ++]-'0' ); val[++ top] = v; i --; //第一个for i会加一次 } else if ( priority ( op[i] ) == 2 ) //*/时也算前面的*/ { if ( front >= 0 && priority ( sign[front] ) == 2 ) { double b = val[top --]; double a = val[top --]; //printf ( "%d.%.2lf %c %.2lf\n", i, a, sign[front], b ); val[++ top] = oper ( a, b, sign[front] ); front --; } sign[++ front] = op[i]; } else { if ( front >= 0 && priority ( sign[front] ) == 2 ) //**当符号为+-时也只能算前面的*/,不然优先会有问题,看特殊数据 { double b = val[top --]; double a = val[top --]; //printf ( "%d.%.2lf %c %.2lf\n", i, a, sign[front], b ); val[++ top] = oper ( a, b, sign[front] ); front --; } sign[++ front] = op[i]; //符号入栈 } } if ( front >= 0 && priority ( sign[front] ) == 2 ) //最后一个符号可能是*/,需要先算 { double b = val[top --]; double a = val[top --]; //printf ( "%.2lf %c %.2lf\n", a, sign[front], b ); val[++ top] = oper ( a, b, sign[front] ); front --; } ans = val[0]; for ( int i = 0; i <= front; i ++ ) //没算的只剩+-,按顺序算 { double b = val[i+1]; //printf ( "%.2lf %c %.2lf\n", ans, sign[i], b ); ans = oper ( ans, b, sign[i] ); } printf ( "%.2lf\n", ans ); } return 0; } /* - / - + 算+的时候最后一个else开始写的有问题 */
相关文章推荐
- HDOJ 题目2852 KiKi's K-Number(线段树求大于a的第k值)
- 51nod 1378:夹克老爷的愤怒 很好玩的一道树状dp
- 黑马程序员—Java基础—IO5
- 51nod 1378:夹克老爷的愤怒 很好玩的一道树状dp
- LA 1453 旋转卡壳
- iptables详解
- 客户端用HttpURLConnection向php服务器上传图片
- 关于Fragment懒加载的学习和使用+参数传递的方法
- 希尔排序
- 2015.11.4
- c++模板特化
- C# 编写短信发送Window服务
- Codeforces Round #328 (Div. 2)
- 枚举类型的作用
- NOSQL的类型及其特点
- 网络图片查看器(子线程与消息传递)
- 被风吹了这么些年,为什么物联网一直不在风口上?(一)
- NOI题库2.4 1788 Pell数组
- 10001---JavaWeb开发基础--初识Tomcat
- 天声人語 20151104 別姓、最高裁を動かすか