csp 201903-2 二十四点

本文介绍了一个用于解决24点游戏的计算器程序,通过将中缀表达式转换为后缀表达式,并考虑运算符优先级,实现对输入的四则运算表达式进行计算,判断其结果是否为24。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

201903-2 二十四点

理解:写一个简单的计算器程序,判断结果是否为24;

计算器程序原理:
1.中缀表达式 转为 后缀表达式
2.计算后缀表达式
3.涉及到 计算符号的 优先级
参考:

在这里插入图片描述
代码

//24点
#include<iostream>
#include<stack>
#include<string>
using namespace std;

int to_int(char c){
	return c - '0';
}

int to_r(char c){
	if (c == 'x' || c == '/')return 2;
	else if(c=='+'||c=='-')return 1;
}

int op(int a, int b, char c){
	if (c == 'x'){
		return a*b;
	}
	else if (c == '+'){
		return a + b;
	}
	else if (c == '-'){
		return a - b;
	}
	else{
		return a/b;
	}
}

int main(){
	int n; cin >> n;
	stack<char> st1,st2;
	stack<int> st3;
	string str; 
	for (int i = 0; i < n; i++){
        cin >> str;
		for (int j = 0; j < 7; j++){
			if (str[j] >= '0'&&str[j] <= '9'){			
				st1.push(str[j]);
			}
			else{
				if (st2.empty()){
					st2.push(str[j]);
				}
				else if (to_r(str[j]) > to_r(st2.top())){
					st2.push(str[j]);
				}
				else if (to_r(str[j]) <= to_r(st2.top())){
					char c;
					while (!st2.empty()&&to_r(str[j]) <= to_r(st2.top())){
						c = st2.top();
						st2.pop();
						st1.push(c);
					}
					st2.push(str[j]);
				}
			}
		}
		while (!st2.empty()){
			char c1 = st2.top();
			st2.pop();
			st1.push(c1);
		}
		while (!st1.empty()){
			st2.push(st1.top());
			st1.pop();
		}
		while (!st2.empty()){
			if (st2.top() >= '0'&&st2.top() <= '9'){
				st3.push(to_int(st2.top()));
				st2.pop();
			}
			else{
				int aa = st3.top(); st3.pop();
				int bb = st3.top(); st3.pop();
				st3.push(op(bb, aa, st2.top()));
				st2.pop();
			}
		}
		//cout << st3.top() << endl;
		if (st3.top() == 24){
			cout << "Yes" << endl;
		}
		else{
			cout << "No" << endl;
		}
		while (!st2.empty()){
			st2.pop();
		}
		while (!st1.empty()){
			st1.pop();
		}
		while (!st3.empty()){
			st3.pop();
		}
	}
	//system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码个稀巴烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值