题目

请添加图片描述
请添加图片描述

答案

python答案

try:
    s = input()
    print("{:.2f}".format(eval(s)))
except:
    print("输入错误")

c++ 答案

#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int main()
{
	stack<double> s1;
	stack<char> s2;
	char str[30],tmp;
	gets(str);
	int n=strlen(str),flag=0;
	double tmp1,tmp2;
	for(int i=0;i<n;i++)
	{
		if(str[i]>='0'&&str[i]<='9')
		{
			if(flag==0)
			{
				s1.push(str[i]-'0');
				flag=1;
			}	
			else if(flag==1)
			{
				if(s2.top()=='*')
				{
					tmp1=s1.top();s1.pop();
					tmp2=tmp1*(str[i]-'0');
					s1.push(tmp2);
					s2.pop();
				}
				else if(s2.top()=='/')
				{
					tmp1=s1.top();s1.pop();
					if(str[i]=='0')
					{
						printf("输入错误");
						return 0;
					}
					tmp2 = tmp1/(int)(str[i]-'0');
					s1.push(tmp2);
					s2.pop();
				}
				else if((s2.top()=='+')||(s2.top()=='-'))
		   		{
		   			s1.push(str[i]-'0');
				}
			}
		}
		else if((str[i]=='+')||(str[i]=='-')||(str[i]=='*')||(str[i]=='/')) s2.push(str[i]);
		else if(str[i]!=' ') 
		{
			printf("输入错误");
			return 0;
		}
	} 
	while(s1.size()!=1)
	{
		tmp1=s1.top();s1.pop();
		tmp2=s1.top();s1.pop();
		if(s2.top()=='+')
		{
			s1.push(tmp1+tmp2);
			s2.pop();
		}
		else if(s2.top()=='-')
		{
			s1.push(tmp2-tmp1);
			s2.pop();
		}
	}
	printf("%.2lf",s1.top());
} 

总结

这道题要使用巧劲,不能硬算

比如这道题,我刚开始看就在想运算优先级、乘除怎么处理啥的,即我上来想的就是硬算,但不论是python题还是c++的题,我们在最开始读完题后首先想的应该是有没有简单、适合的方法能够较容易地解决这道题

比如,例题给的字符串:

1+3 * 5   -6/2

本身就和13的字符串类型是等价的,只不过一个是算数表达式,一个是计算的结果罢了

希望能通过这道题给大家一些做题的启示,尽可能地避免犯我和类似的错误
(c++版本是我在做这道题时,想着能不能用c++的堆栈实现,于是自己尝试了一下,大家仅作参考)

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐