将中缀表达式转换为后缀表达式并计算(包含小数)

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/*包含小数的中缀表达式转换后缀表达式*/

public class PolandTest {
   
    public static void main(String[] args) {
   

        //将此中缀表达式转换为后缀表达式,先将中缀表达式放入list里
        String expression = "1.3+((2.15+3.3)*4)-5.25";
        List list = changeToList(expression);
        System.out.println("中缀表达式为:" + list);
        List postfixExpression = postfixExpression(list);
        System.out.println("后缀表达式为:" + postfixExpression);

        //计算后缀表达式的结果
        System.out.println(calculator(postfixExpression));
    }

    public static List<String> changeToList(String s){
   

        int i = 0; //表示遍历string的指针
        List<String> ls = new ArrayList<String>();//定义一个新的List
        char c ;//字符串的拼接放入到ch中,每遍历一个字符,就放到ch中
        String str;//多位数的拼接
        do{
   
            //如果是数字
            if((c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57 || c == '.'){
   
                str 
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为你写一个把含小数和负数的中缀表达式转换后缀表达式的函数。 思路如下: 1. 定义一个栈,保存运算符和左括号。 2. 遍历中缀表达式的每个元素。 3. 如果是数字,直接输出。 4. 如果是左括号,入栈。 5. 如果是右括号,将栈中运算符弹出并输出,直到遇到左括号。 6. 如果是运算符,弹出栈中所有优先级大于或等于该运算符的运算符,并输出,然后将该运算符入栈。 7. 遍历完整个表达式后,将栈中所有运算符弹出并输出。 以下是代码实现: ```c++ #include <iostream> #include <stack> #include <string> #include <sstream> #include <cmath> using namespace std; // 判断是否是运算符 bool isOperator(char c) { return (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')'); } // 比较运算符优先级 int priority(char op) { if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/') { return 2; } else { return 0; } } // 将中缀表达式转换后缀表达式 string infixToPostfix(string infix) { stack<char> s; stringstream ss; char c; for (int i = 0; i < infix.length(); i++) { c = infix[i]; // 是数字,直接输出 if (isdigit(c) || c == '.') { ss << c; } // 是运算符 else if (isOperator(c)) { // 如果是负数,则加上一个0 if (c == '-' && (i == 0 || isOperator(infix[i - 1]))) { ss << "0 "; } // 如果是左括号,入栈 else if (c == '(') { s.push(c); } // 如果是右括号,弹出栈中的运算符并输出,直到遇到左括号 else if (c == ')') { while (s.top() != '(') { ss << s.top() << " "; s.pop(); } s.pop(); } // 如果是其他运算符,弹出栈中所有优先级大于或等于该运算符的运算符,并输出,然后将该运算符入栈 else { while (!s.empty() && s.top() != '(' && priority(s.top()) >= priority(c)) { ss << s.top() << " "; s.pop(); } s.push(c); } } } while (!s.empty()) { ss << s.top() << " "; s.pop(); } return ss.str(); } int main() { string infix = "2.5+(3-1)*4-3/2"; string postfix = infixToPostfix(infix); cout << postfix << endl; // 输出:2.5 3 1 - 4 * + 3 2 / - return 0; } ``` 希望能帮助到你。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值