数据结构(实验三)栈和队列 —— 3.后缀式求值

这篇博客介绍了如何使用后缀表达式(逆波兰表示法)进行计算,并展示了两种不同的实现方式,一种基于C语言,另一种利用C++的栈数据结构。文章探讨了为何计算机更倾向于后缀式,并提供了输入后缀表达式求值的代码示例,输出结果保留一位小数。

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

7-3 后缀式求值

我们人类习惯于书写“中缀式”,如 3 + 5 * 2 ,其值为13。 (p.s. 为什么人类习惯中缀式呢?是因为中缀式比后缀式好用么?)
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是: 3 5 2 * + 
现在,请对输入的后缀式进行求值。

输入格式:

在一行中输入一个后缀式,运算数运算符之间用空格分隔,运算数长度不超过6位,运算符仅有+ - * / 四种。

输出格式:

在一行中输出后缀式的值,保留一位小数。

输入样例:

3 5.4 2.2 * +

结尾无空行

输出样例:

14.9

结尾无空行

#include <stdio.h>

int main()
{
    char str[10];
    double st[100];
    int i=0;
    while(~scanf("%s", str))
    {
        if(str[1] == '\0' && (str[0] == '+'||str[0] == '-'||str[0] == '*'||str[0] == '/'))
        {
            double num1, num2, res;
            num1 = st[--i];
            num2 = st[--i];
            switch(str[0])
            {
            case '+':
                res = num2 + num1;
                st[i++]=res;
                break;
            case '-':
                res = num2 - num1;
                st[i++]=res;
                break;
            case '*':
                res = num2 * num1;
                st[i++]=res;
                break;
            case '/':
                res = num2 / num1;
                st[i++]=res;
                break;
            }
        }
        else
        {
            double number;
            sscanf(str, "%lf", &number);
            //sscanf()会将参数str 的字符串根据参数format(格式化字符串)来转换并格式化数据, 转换后的结果存于对应的变量中。
            st[i++]=number;
        }
    }
    printf("%.1lf", st[0]);
    return 0;
}

栈实现

#include <iostream>
#include <string>
#include <stack>             //栈头文件
#include <iomanip>

using namespace std;

int main()
{
	string str;
	stack<double> s;         //创建一个double栈

	while (cin >> str)
	{
		if (str == "+" || str == "-" || str == "*" || str == "/")
		{
			double a, b;
			a = s.top();
			s.pop();
			b = s.top();
			s.pop();

			if (str == "+")
				s.push(b + a);
			else if (str == "-")
				s.push(b - a);
			else if (str == "*")
				s.push(b * a);
			else
				s.push(b / a);
		}
		else
			s.push(stod(str));      //stod()将str里的元素转换为double类型
	}
	cout << fixed << setprecision(1) << s.top();

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

趟水过河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值