简单计算器
程序员文章站
2022-07-14 08:37:29
...
类型一:
输入:当一行中只有0时输入结束
输出:对每个测试用例输出一行,精确到小数点后两位
备注:这个题的细节是可以输入浮点数,书上的代码是只能输入整型数字
#include <stdio.h>
#include <iostream>
#include <stack>
#include <queue>
#include <map>
#include <string>
using namespace std;
struct node
{
double num;
char op;
bool flag;
}Node;
stack<node> s;
queue<node> q;
string str;
map<char, int> op;
void Change()
{
node temp;
for(int i = 0; i < str.length();)
{
if(str[i] >= '0' && str[i] <= '9')
{
temp.flag = true;
temp.num = str[i++] - '0';
if(str[i] == '.')
{
i++;
double product = 0.1; //这里写错
while(i < str.length() && str[i] >= '0' && str[i] <= '9')
{
temp.num = temp.num + (str[i] - '0') * product;
product = product * 0.1;
i++;//这一句漏了
}
}
while(i < str.length() && str[i] >= '0' && str[i] <= '9')
{
temp.num = temp.num * 10 + (str[i] - '0');
i++;
}
q.push(temp);
}
else
{
temp.flag = false;
while(!s.empty() && op[s.top().op] >= op[str[i]])
{
q.push(s.top());
s.pop();
}
temp.op = str[i];
s.push(temp);
i++;//这一句漏了
}
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
}
double Cal()
{
double temp1, temp2;
node cur, temp;
while(!q.empty())
{
cur = q.front();
q.pop();//这句漏了
if(cur.flag == true) //这里写成1了
{
s.push(cur);
}
else
{
temp2 = s.top().num;
s.pop();
temp1 = s.top().num;
s.pop();
temp.flag = true;//漏了
if(cur.op == '+')
{
temp.num = temp1 + temp2;
}
else if(cur.op == '-')
{
temp.num = temp1 - temp2;
}
else if(cur.op == '*')
{
temp.num = temp1 * temp2;
}
else
temp.num = temp1 / temp2;
s.push(temp);
}
}
return s.top().num;
}
int main(void)
{
op['+'] = op['-'] = 1;
op['*'] = op['/'] = 2;
while(getline(cin, str), str != "0")
{
for(string::iterator it = str.begin(); it != str.end(); it++)//这里写成it--了
{
if(*it == ' ')
{
str.erase(it);
}
}
while(!s.empty())
{
s.pop();
}
Change();
printf("%.2f\n", Cal());
}
return 0;
}
上一篇: datagrid选中行