HDU-1237
来源:互联网 发布:男士保湿面霜知乎 编辑:程序博客网 时间:2024/05/21 08:39
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
思路:
加减乘除可用栈来做,此题有点注意的是要读取空格。
代码如下:
#include<iostream>#include<cstring>#include<string>#include<stack>#include<algorithm>#include<cstdio>using namespace std;int main(){double n, temp; char b; char c[2];while (scanf("%lf%c",&n,&b)){if (n == 0 && b == '\n')break; //程序结束条件double ans = 0;stack<double>s; //声明栈s.push(n);//压进栈while (scanf("%s %lf",c,&n)!=EOF) //字符串c读取符号与一个空格{if (c[0] == '+')s.push(n); else if (c[0] == '-')s.push(-n);else if (c[0] == '*') //取出栈顶元素进行运算{temp = n*s.top(); s.pop();s.push(temp);}else //取出栈顶元素进行运算{temp = s.top() / n;s.pop();s.push(temp);}if (b = getchar(), b == '\n')break; //读取一个空格}while (!s.empty()) //此时栈中的元素是正或者负 只需相加即可 {ans += s.top();s.pop();}printf("%.2lf\n", ans); }return 0;}
阅读全文
1 0
- hdu 1237
- hdu-1237
- HDU 1237
- hdu 1237
- hdu 1237
- HDU 1237
- HDU 1237
- hdu 1237
- HDU 1237
- Hdu 1237
- HDU 1237
- HDU-1237
- HDU 1237
- HDU 1237 简单计算器
- HDU 1237 简单计算器
- HDU 1237 前缀树
- hdu 1237 简单计算器
- HDU 1237 简单计算器
- HTML5 语义相关元素标签
- redis字符串操作
- (1)Qt利用QSerialPort使用串口
- 51Nod--1003 阶乘后面0的数量
- A. Vladik and Courtesy
- HDU-1237
- 精通Dubbo——Dubbo配置文件详解
- 中介者模式
- HDU-1874-畅通工程续(最短路 未队列优化)
- 把锂电池塞进鼠标
- (2)Qt中串口的数据处理
- 关于Android studio的安装教程
- mysql语法错误的小经验
- 记录异常日志的七条规则