首页 > 代码库 > 表达式求值
表达式求值
#include <bits/stdc++.h>using namespace std;char OprateRelation[7][7] =// + - * / ( ) = {{‘>‘,‘>‘, ‘<‘, ‘<‘, ‘<‘, ‘>‘, ‘>‘}, //‘+‘ {‘>‘, ‘>‘, ‘<‘, ‘<‘, ‘<‘, ‘>‘, ‘>‘}, //‘-‘ {‘>‘, ‘>‘, ‘>‘, ‘>‘, ‘<‘, ‘>‘, ‘>‘}, //‘*‘ {‘>‘, ‘>‘, ‘>‘, ‘>‘, ‘<‘, ‘>‘, ‘>‘}, //‘/‘ {‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘=‘, ‘ ‘}, //‘(‘ {‘>‘, ‘>‘, ‘>‘, ‘>‘, ‘ ‘, ‘>‘, ‘>‘}, //‘)‘ {‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘ ‘, ‘=‘}};//‘=‘string Operteraiton = "+-*/()=";int Getoperteration(char x) { for(int i = 0; i < 7; i++) if(Operteraiton[i] == x) return i; return -1;}char CompareOperation(char x, char y) { return OprateRelation[Getoperteration(x)][Getoperteration(y)];}double Get_ans(double x, double y, char opt) { if(opt == ‘-‘) return x - y; else if(opt == ‘+‘) return x + y; else if(opt == ‘*‘) return x * y; else return x/y;}double Slove(string Pattern) { stack <double> Num; stack <char> Opertion; Opertion.push(‘=‘); int i = 0, flag = 1, gg = 1; char Next_char; if(Pattern[0] == ‘+‘ || Pattern[0] == ‘-‘) Num.push(0); if(Pattern[Pattern.size() - 1] != ‘=‘) Pattern += ‘=‘; while(flag && i < Pattern.size()) { Next_char = Pattern[i]; if(Getoperteration(Next_char) < 0) { string Number = ""; Number += Next_char; while(Getoperteration(Pattern[++i]) < 0) { Number += Pattern[i]; } Num.push(atof(Number.c_str())); }else { char opt = CompareOperation(Opertion.top(), Next_char); if(opt == ‘<‘) { Opertion.push(Next_char); i++; }else if(opt == ‘>‘) { char Next_option = Opertion.top(); Opertion.pop(); double y = Num.top(); Num.pop(); double x = Num.top(); Num.pop(); double ans = Get_ans(x, y, Next_option); Num.push(ans); }else { Opertion.pop(); if(i == (int)Pattern.length()) flag = 0; else i++; } } } return Num.top();}int main(){ int T; cin >> T;//测试用例的个数 string s; while(T--) { cin >> s; printf("%.2f\n", Slove(s)); } return 0;}
表达式求值
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。