HDU 1237 简单计算器

Problem Description

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。

Input

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

Output

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

Sample Input

1 + 2
4 + 2 * 5 - 7 / 11
0

Sample Output

3.00

13.36

string 读入

#include<stdio.h>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<stack>
using namespace std;
string s;
stack<double> a;
stack<char>b;
double x, y;
char c, z;

bool check(char x, char y)
{
	if (x == '*' || x == '/') return true;
	if (y == '+' || y == '-') return true;
	return false;
}

int main()
{
	while (getline(cin, s), s != "0")
	{
		s = s + ' ' + 'A';
		stringstream ss(s);
		while (ss >> x >> c)
		{
			a.push(x);
			while (!b.empty() && (c == 'A' || check(b.top(), c)))
			{
				x = a.top(); a.pop();
				y = a.top(); a.pop();
				z = b.top(); b.pop();
				switch (z){
				case '+':a.push(x + y); break;
				case '-':a.push(y - x); break;
				case '*':a.push(x * y); break;
				case '/':a.push(y / x); break;
				}
			}
			if (c != 'A') b.push(c);
		}
		printf("%.2f\n", a.top());
		while (!a.empty()) a.pop();
	}
	return 0;
}
char 读入
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int i;
double x, y;
char s[250], z;

bool check(char x, char y)
{
	if (x == '*' || x == '/') return true;
	if (y == '+' || y == '-') return true;
	return false;
}

int main()
{
	while (gets(s), strcmp(s, "0") != 0)
	{
		stack<char> b;
		stack<double> a;
		for (i = 0; s[i]; i++)
		{
			if (s[i] == ' ') continue;
			if (s[i] >= '0'&&s[i] <= '9')
			{
				x = 0;
				while (s[i] >= '0'&&s[i] <= '9')
				{
					x = x * 10 + s[i] - '0';
					i++;
				}
				i--;
				a.push(x);
			}
			if (s[i] < '0' || s[i] > '9' || !s[i + 1])
			{
				while (!b.empty() && (!s[i + 1] || check(b.top(), s[i])))
				{
					x = a.top(); a.pop();
					y = a.top(); a.pop();
					z = b.top(); b.pop();
					switch (z){
					case '+':a.push(x + y); break;
					case '-':a.push(y - x); break;
					case '*':a.push(x * y); break;
					case '/':a.push(y / x); break;
					}
				}
				b.push(s[i]);
			}
		}
		printf("%.2lf\n", a.top());
	}
	return 0;
}

注意头文件要用stdio.h,用cstdio一直wa,搞不懂。

你可能感兴趣的:(栈,HDU)