c++多位数的浮点数运算中缀表达式求和,可用于多位整型数
例题
求中缀表达式
( 34 - 72.3 ) * 54.7 - 82.4 的值
原理
运用两个栈
stack<char>s;
//存放运算符
stack<double>ss;
//存放浮点数
话不多说上代码
// c++浮点数的中缀表达式求和
#include<iostream>
#include<fstream>
#include<cmath>
#include<stack>
using namespace std;
int Getpriority(char ch) {//确定优先级
//+ -:1
//* /:2
if (ch == '+' || ch == '-') {
return 1;
}
else if (ch == '*' || ch == '/') {
return 2;
}
}
bool IsOperator(char ch)//判断是否为运算符
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
return true;
return false;
}
double operations(char t, double left, double right) {//运算
double sum;
switch (t) {
case '+':
sum = left + right;
break;
case '-':
sum = left - right;
break;
case '*':
sum = left * right;
break;
case '/':
if (right != 0) {
sum = left / right;
break;
}
else {
cout << "error" << endl;
exit(0);
}
}
return sum;
}
void Infix_summation(char* cur) { //中缀求和
stack<char> s;//存放运算符
stack<double>ss;//存放浮点数
char* c = cur;
while (*c != '\0') {
if (*c == ' ') {
c++;
continue;
}
else if (*c >= '0' && *c <= '9') {
double t = *c - '0';
c++;
while (*c >= '0' && *c <= '9') {
t = t * 10 + *c - '0';
c++;
}
if (*c == '.') {
c++;
int i = 1;
while (*c >= '0' && *c <= '9') {
t = t + pow(0.1, i) * (*c - '0');
i++;
c++;
}
}
ss.push(t);
}
else if (IsOperator(*c)) {
if (s.empty()) {
s.push(*c);
c++;
}
else if (Getpriority(*c) > Getpriority(s.top())) {
s.push(*c);
c++;
}
else if (Getpriority(*c) <= Getpriority(s.top())&&s.top()!='(') {
loop1: char t = s.top();
s.pop();
double right = ss.top();
ss.pop();
double left = ss.top();
ss.pop();
double sum;
sum = operations(t, left, right);
ss.push(sum);
if (!s.empty() && Getpriority(*c) <= Getpriority(s.top())&&s.top()!='(') {
goto loop1;
}
s.push(*c);
c++;
}
else if(s.top()=='('){
s.push(*c);
c++;
}
}
else if(*c=='('){
s.push(*c);
c++;
}
else if (*c == ')') {
loop2: if (s.top() != '(') {
char t = s.top();
s.pop();
double right = ss.top();
ss.pop();
double left = ss.top();
ss.pop();
double sum;
sum = operations(t, left, right);
ss.push(sum);
}
if (!s.empty() && s.top() != '(') {
goto loop2;
}
s.pop();
c++;
}
}
while (!s.empty()) {
char t = s.top();
s.pop();
double right = ss.top();
ss.pop();
double left = ss.top();
ss.pop();
double sum;
sum = operations(t, left, right);
ss.push(sum);
}
double tmp = ss.top();
cout << tmp << endl;
}
void Test()
{
char posture[1000] = "( 34 - 72.3 ) * 54.7 - 82.4 ";
Infix_summation(posture);
}
int main()
{
Test();
return 0;
}
运行结果
如果有兴趣讨论加我QQ
1771605689