ccf&csp 计算机职业资格认证考试 201903-2 24点 c++

 

 

 

 

 

 具体c++实现如下:

#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>

using namespace std;

stack <int> number;     //存储数字
stack <char> symbol;    //存储符号
queue <int> flag;       //存储标志,判断每一次的运算结果是否为24,是24则push(1),否则push(0)

int main(){
	int n;
	char str[10];
	scanf("%d",&n);
	getchar();
	for(int i = 0;i < n;i++){
		gets(str);
		
		//清空栈,开启下一次循环
		while(!number.empty())
			number.pop();
		while(!symbol.empty())
			symbol.pop();
		for(int j = 0;j < strlen(str);j++){
			//判断字符为数字还是符号
			if(str[j] > '0' && str[j] <= '9'){
				number.push(str[j] - '0');
			} 
			else if(str[j] == '+'){
				symbol.push(str[j]);
			}
			else if(str[j] == '-'){        //若是减号,则转换为‘+’号存入,方便计算
				number.push((str[j + 1] - '0')*(-1));
				symbol.push('+');
				j++;
			}
			else if(str[j] == 'x'){
				int temp1 = number.top();
				number.pop();
				number.push(temp1 * (str[j + 1] - '0'));
				j++;
			}
			else{
				int temp2 = number.top();
				number.pop();
				number.push(temp2 / (str[j+1] - '0'));
				j++;
			}
		}
		//计算加法
		while(!symbol.empty()){ //计算剩余的加法 
			int rhs=number.top();
			number.pop();
			int lhs=number.top();
			number.pop();
			symbol.pop();
			number.push(lhs+rhs);
		}
		int result = number.top();
		number.pop();
		if(result == 24)
			flag.push(1);
		else
			flag.push(0);
	}
	while(!flag.empty()){
		int fl = flag.front();
		flag.pop();
		if(fl == 1)
			printf("Yes\n");
		else
			printf("No\n");
	}
	return 0;
}

 有更好的解决办法欢迎大家评论区讨论!

猜你喜欢

转载自blog.csdn.net/qq_47403671/article/details/120297183