算数表达式求值简单版,中缀转后缀运算,c++输出小数点位数控制

本文介绍了一种用于计算包含数字和基本算术运算符(+,-,*,/)的算术表达式的算法。该算法首先将中缀表达式转换为后缀表达式,然后使用两个栈(一个用于数字,一个用于运算符)来求解表达式的值。通过遍历表达式,遇到数字直接入栈,遇到运算符则与栈顶运算符比较优先级,进行相应的计算。

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

算术表达式求值

题目内容:

输入一个由数字、+,-,*,/ 组成的算术表达式,求其值。

输入描述

一个表达式,其中每个运算数为正整数

输出描述

计算结果,保留2位小数

输入样例

1+12*3-4/2

输出样例

35.00

这里先将中缀转为后缀, 没有括号的情况比较简单, 转换规则为
1. 设置两个stack, num和ope
2. 遍历表达式串
3. 遇到数字直接入num
4. 遇到操作符有两种情况
==1. ope为空直接入ope栈
==2. ope不为空则与 ope.top() (设其为top)进行比较
=====a. 若top优先级更低则直接入ope栈
=====b. top优先级更高, 则取num两个数字与top运算, 结果入num栈,继续与新的ope.top()比较, 若把ope比较空了则操作符直接入栈
5. 遍历完了后, ope不为空的话重复取num两个数字与ope.top()运算, 结果入num栈, 直至ope空

代码如下

#include<iostream> 
#include<algorithm>
#include<vector>
#include<string>
#include<memory.h>
#include<queue>
#include<cmath>
#include<iomanip>
#include<stack>
using namespace std;
string str;
stack<double> n;
stack<char> o;

bool is_num(char a)
{
	if(a <= '9' && a >= '0') return true;
	return false;
}

int get(char c)
{
	if(c == '*' || c == '/') return 2;
	return 1;
}

double cal(double a, char c, double b)
{
	if(c == '+') return a + b;
	if(c == '-') return a - b;
	if(c == '*') return a * b;
	return a / b;
}

double solve()
{
	int len = str.length();
	for(int i = 0; i < len; i++)
	{
		if(is_num(str[i]))				//遇到数字字符要取出完整数字来
		{
			int temp = 0;
			while(i < len && is_num(str[i]))
				temp = temp * 10 + str[i++] - '0';
			i--;
			n.push(temp);
		}
		else
		{
			if(o.empty())       		//ope is empty
				o.push(str[i]);
			else
			{
				while(!o.empty() && get(o.top()) > get(str[i]))    
				{
					double num1 = n.top();
					n.pop();
					double num2 = n.top();
					n.pop();
					n.push(cal(num2, o.top(), num1));
					o.pop();
				}
				o.push(str[i]);
			}
		}
	}

	while(!o.empty())
	{
		double num1 = n.top();
		n.pop();
		double num2 = n.top();
		n.pop();
		n.push(cal(num2, o.top(), num1));
		o.pop();
	}

	return n.top();
}

int main()
{
	ios::sync_with_stdio(false);
	cin >> str;
	cout<<setiosflags(ios::fixed)<<setprecision(2)<<solve();
}

c++中设置输出的函数在头文件 中, setprecision(x) 设置有效数字为x位, setiosflags(ios::fixed)将浮点数以固定小数点位数显示, 两个合起来实现固定小数点后有效位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值