PTA 3.11表达式转换

在PTA平台的3.11题目中遇到了一个测试用例无法通过的情况,急需寻求解决方案。目前的问题点在于表达式转换的部分,可能是算法或者逻辑上存在疏漏。期待社区的高手能够提供指导和帮助。

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

有一个测试点过不了,希望大家指点。

/*
 * 1.cpp
 *
 *  Created on: 2017年8月23日
 *      Author: Administrator
 */

#include <bits/stdc++.h>
using namespace std ;
int main()
{
	string s;
	cin>>s;
	stack<char> st;
	bool flag = false;
	for( int i = 0; i < s.length()&&s.length()<=20; i++){
//		负数情况
		if( i == 0 && s[i] == '-'){
				cout<<s[i];
		}
//		多位数及小数
		else if(isdigit(s[i])||s[i]=='.')
		{
			if(i>0&&(isdigit(s[i-1])||s[i-1]=='.')){
				cout<<s[i];
			}
			else if(!flag){
				flag = true;
				cout<<s[i];
			}
			else{
				cout<<" "<<s[i];
			}
		}
//		左括号
		else if(s[i]=='('){
			st.push(s[i]);
		}
//		右括号
		else if(s[i]==')'){
			while(st.top()!='('){
				if(!flag)
				{
					flag = true;
					cout<<st.top();
				}
				else
				{
					cout<<" "<<st.top();
				}
				st.pop();
			}
			st.pop();
		}
//		+,— 号
		else if(s[i]=='+'||s[i]=='-'){
			//			括号内有负数,直接输出
			if(s[i-1]=='('){
				if(s[i]=='-'){
					if(!flag)
					{
						flag = true;
						cout<<s[i]<<s[i+1];
						i++;
					}
					else
					{
						cout<<" "<<s[i]<<s[i+1];
						i++;
					}
				}
			}
			//			优先级问题
			else{
				if(!st.empty()){
				while(!st.empty()&&(st.top()=='*'||st.top()=='/')){
					if(!flag)
					{
						flag = true;
						cout<<st.top();
					}
					else
					{
						cout<<" "<<st.top();
					}
					st.pop();
				}

				while(!st.empty()&&(st.top() == '+' || st.top() == '-')){
					if(!flag)
					{
						flag = true;
						cout<<st.top();
					}
					else
					{
						cout<<" "<<st.top();
					}
					st.pop();
				}
				}
				st.push(s[i]);
			}
			}
//		*、/号
		else if(s[i]=='*'||s[i]=='/'){
			if(!st.empty()){
			while(!st.empty()&&(st.top()=='*'||st.top()=='/')){
				if(!flag)
				{
					flag = true;
					cout<<st.top();
				}
				else
				{
					cout<<" "<<st.top();
				}
				st.pop();
			}
			}
			st.push(s[i]);
		}

	}

	while(!st.empty()){
		if(!flag)
		{
			flag = true;
			cout<<st.top();
		}
		else
		{
			cout<<" "<<st.top();
		}
		st.pop();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值