数值运算——python(附带c++答案以及总结)

题目

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

答案

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++的堆栈实现,于是自己尝试了一下,大家仅作参考)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值