版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/84076140
简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 27155 Accepted Submission(s): 9861
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
思路:计算器的运算优先级用栈来实现最适合不过了,只要在入栈之前控制好
* / + -这样的优先级顺序,getchar来读入每个运算符以及吃掉空格即可。
AC Code:
/*
Problem : 1237 ( 简单计算器 ) Judge Status : Accepted
RunId : 27199222 Language : G++ Author : html_11
*/
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<list>
#define mod 998244353
#define INF 0x3f3f3f3f
#define Min 0xc0c0c0c0
#define mst(a) memset(a,0,sizeof(a))
#define f(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 5;
stack<double>s;
int main(){
int n;
double m;
while(scanf("%d", &n) != EOF){
char c = getchar();
if(c == '\n' && n == 0) break;
s.push(n);
c = getchar();
while(scanf("%d", &n) != EOF){
if(c == '*'){
m = s.top();
m *= n;
s.pop(); //这里要记得出栈
s.push(m);
}
else if(c == '/'){
m = s.top();
m /= n;
s.pop(); //这里记得出栈
s.push(m);
}
else if(c == '+'){
s.push(n);
}
else if(c == '-'){
s.push(0 - n);
}
c = getchar();
if(c == '\n') break;
c = getchar();
}
double res = 0;
while(!s.empty()){
res += s.top();
s.pop(); //栈要清空:细节
}
printf("%.2lf\n", res);
}
return 0;
}