CSP 201903-2 二十四点 栈-中缀表达式求值※※

201903-2 二十四点

1.功能函数

bool isNumber(char ch)
bool isOperator(char ch)
int calculate(char ch, int a, int b)

2.get函数

char ch=cin.get();
char ch=file.get();
char ch;
cin.get(ch);
char ch;
file.get(ch);
cin.get();

注意:get()会吸收前面打的回车,所以用get()之前先用cin.get()吸收掉回车,否则会出错

3.字符型与整型的转换

char ch='1';
int a=(int)ch;//a=49;
int b=(int)ch-'0';//b=1;
int c=(int)(ch-'0');//c=1;

但第二种应该是不好的,整型与字符型运算 

4.栈

#include<stack>
stack<int> s;//定义
s.push(x);//入栈
s.pop();//删除栈顶元素,不返回值
int a=s.top();//返回栈顶元素
int length=s.size();//栈中元素个数
s.empty();//栈空返回true

MyAnswer 

#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool isNumber(char ch)
{
	if (ch >= '1'&&ch <= '9')
		return 1;
	else
		return 0;
}
bool isOperator(char ch)
{
	if (ch == '+' || ch == '-' || ch == 'x' || ch == '/')
		return 1;
	else
		return 0;
}
int calculate(char ch, int a, int b)
{
	int result = 0;
	switch (ch)
	{
	case'+':
		result = b + a;
		break;
	case'-':
		result = b - a;
		break;
	case'x':
		result = b * a;
		break;
	case'/':
		result = b / a;
		break;
	}
	return result;
}
int main()
{
	int n;
	cin >> n;
	string *array = new string[n];
	for (int i = 0; i < n; i++)
	{
		cin.get();
		char ch, c;//ch存储输入,c存储操作符栈顶元素
		int result, a, b;//result存储计算结果
		stack<int>numStack;
		stack<char>chStack;
		cin.get(ch);
		numStack.push((int)(ch - '0'));
		for (int i = 1; i < 7; i++)
		{
			cin.get(ch);
			if (isOperator(ch) == 1)
				chStack.push(ch);
			else if (isNumber(ch) == 1)
			{
				c = chStack.top();
				if (c == '+' || c == '-')
					numStack.push((int)(ch - '0'));
				else if (c == 'x')
				{
					a = (int)(ch - '0');
					b = numStack.top();
					result = calculate('x', a, b);
					chStack.pop();
					numStack.pop();
					numStack.push(result);
				}
				else if (c == '/')
				{
					a = (int)(ch - '0');
					b = numStack.top();
					result = calculate('/', a, b);
					chStack.pop();
					numStack.pop();
					numStack.push(result);
				}
			}
		}
		int sum = 0;
		while (!chStack.empty())
		{
			int x = numStack.top();
			char y = chStack.top();
			sum = calculate(y, x, sum);
			numStack.pop();
			chStack.pop();
		}
		sum += numStack.top();
		if (sum == 24)
			array[i] = "Yes";
		else
			array[i] = "No";
	}
	for (int i = 0; i < n; i++)
		cout << array[i] << endl;
	return 0;
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值