表达式转换(测试点)

表达式转换

题目

在这里插入图片描述

答案

#include<stack>
#include<stdio.h>
using namespace std;
int main()
{
	stack<char> s;
	char str[100];
	int flag=0;
	scanf("%s",str);
	for(int i=0;str[i];i++)
	{
		if((str[i]=='-'||str[i]=='+')&&i==0)
		printf("%c",str[i]);
		else if(str[i]=='.') printf(".");
		else if(str[i]>='0'&&str[i]<='9') 
		{			
			if(!(str[i-1]>='0'&&str[i-1]<='9')&&str[i-1]!='.') 
			{
				if(flag==0)
				{
					printf("%c",str[i]);flag=1;
				}
				else printf(" %c",str[i]);
			} 
			else if((str[i+1]>='0'&&str[i+1]<='9')||str[i+1]=='.'||str[i-1]=='.'||(str[i-1]>='0'&&str[i-1]<='9')) printf("%c",str[i]);
			else if(flag==0)
			{
				printf("%c",str[i]);flag=1;
			}
			else printf(" %c",str[i]);			
		}
		else
		{
			if(s.empty()||str[i]=='(') s.push(str[i]);
			else if(str[i]==')')
			{
				while(s.top()!='(') 
				{
					printf(" %c",s.top());
					s.pop();
				}
				s.pop();
			}
			else if((str[i]=='+'||str[i]=='-')&&(str[i-1]=='(')&&(str[i+1]>='0'&&str[i+1]<='9')) 
			{
				if(flag==0) 
				{
					printf("%c",str[i+1]);flag=1;
				}
				else printf(" %c",str[i+1]);	
				i++;
			}
			else if((str[i]=='+'||str[i]=='-')&&(s.top()=='+'||s.top()=='-'||s.top()=='*'||s.top()=='/'))
			{
				printf(" %c",s.top());
				s.pop();
				i--;
			}
			else if((str[i]=='+'||str[i]=='-')&&(s.top()=='(')) s.push(str[i]);
			else if((str[i]=='*'||str[i]=='/')&&(s.top()=='*'||s.top()=='/'))
			{
				printf(" %c",s.top());
				s.pop();
				i--;
			}
			else if((str[i]=='*'||str[i]=='/')&&(s.top()=='+'||s.top()=='-'||s.top()=='(')) s.push(str[i]);
		}
	}
	while(!s.empty())
	{
		printf(" %c",s.top());
		s.pop();
	}
	printf("\n");
}

详细测试点

序号输入输出说明
02+3*(7-4)+8/42 3 7 4 - * + 8 4 / +正常测试6种运算符
1((2+3)*4-(8+2))/52 3 + 4 * 8 2 + - 5 /嵌套括号
21314+25.5*121314 25.5 12 * +运算数超过1位整数且有非整数出现
3-2*(+3)-2 3 *运算数前有正负号
4123123只有一个数字

(尤其注意序号为2和3的两个测试点)

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值