You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

141 lines
2.9 KiB

2 years ago
#include <iostream>
#include <vector>
using namespace std;
void compares(vector<string> &a,vector<int> &b,int nowsym);
void calculations(vector<string> &a,vector<int> &b,int nowsym);
int main(){
cout << "请输入一个算式,包含加减乘除乘方括号:" << endl;
string s;
cin >> s;
vector<string> num={"x"};
vector<int> symbol;
//1+2- -11*12/ -21^ -31( -32) -40.
cout << "--------------------------------" << endl;
for (auto x:s){
if(x>47&&x<58){
// 数字
if(*(num.end()-1)=="x"){
// 可以输入数字
*(num.end()-1)=to_string(x-'0');
}else{
if(symbol.end()!=symbol.begin()){
if(*(symbol.end()-1)==40){
// 有小数点
symbol.pop_back();
*(num.end()-1)=*(num.end()-1)+"."+to_string(x-'0');
}else{
*(num.end()-1)=*(num.end()-1)+to_string(x-'0');
}
}else{
// 多位数字
*(num.end()-1)=*(num.end()-1)+to_string(x-'0');
}
}
}else{
// 符号
int sym=0;
if(x=='.')sym=40;
if(x=='+')sym=1;
if(x=='-')sym=2;
if(x=='*')sym=11;
if(x=='/')sym=12;
if(x=='^')sym=21;
if(x=='(')sym=31;
if(x==')')sym=32;
if(sym==40){
// 小数点
symbol.push_back(sym);
}else{
// 其他运算符
compares(num,symbol,sym);
}
}
}
// 最后一次计算
compares(num,symbol,0);
cout << "计算结果为:" << *num.begin() << endl;
return 0;
}
void compares(vector<string> &a,vector<int> &b,int nowsym){
// cout << "运算符" << nowsym << endl;
if(b.end()==b.begin()){
// 运算符为空直接添加
b.push_back(nowsym);
if(*(a.end()-1)!="x")a.push_back("x");
return;
}else{
if(((*(b.end()-1)+5)<nowsym)&&nowsym!=32){
// 心量级比较大,直接添加
b.push_back(nowsym);
if(nowsym!=31){
a.push_back("x");
}
return;
}else if(*(b.end()-1)>(nowsym+5)){
// 新量级比较小
if(*(b.end()-1)==31){//遇到左括号(
b.push_back(nowsym);
a.push_back("x");
return;
}
calculations(a,b,nowsym);
compares(a,b,nowsym);
// 进行计算
}else{
if(nowsym==32){
if(*(b.end()-1)==31){
cout << "括号相遇" << endl;
b.pop_back();
// a.push_back("x");
return;
}else{
calculations(a,b,nowsym);
compares(a,b,nowsym);
}
//进行计算后,不添加符号直接返回
}else{
// 同级进行计算
calculations(a,b,nowsym);
compares(a,b,nowsym);
}
}
}
}
void calculations(vector<string> &a,vector<int> &b,int nowsym){
double c1=atof((*(a.end()-1)).c_str());
double c2=atof((*(a.end()-2)).c_str());
int operation=*(b.end()-1);
double value;
a.pop_back();
a.pop_back();
b.pop_back();
if(operation==1){
// +
value=c2+c1;
}else if(operation==2){
// -
value=c2-c1;
}else if(operation==11){
// *
value=c2*c1;
}else if(operation==12){
// /
value=c2/c1;
}else if(operation==21){
// ^
value=pow(c2,c1);
}
a.push_back(to_string(value));
}