這個是主要用到了棧的思想;
下邊是我用來調試的代碼,供大家參考:
#include<iostream>
#include<stack>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
//char a[100];
stack <double>operands;//運算操作數
stack<char> operators;//運算操作符
stack<int> points;//小數的小數部分
int Priority(char a,char b){//判斷優先級
if(b=='\n')if(a=='#')return 0;else return 1;
else if(a=='('){
if(b==')') return 0;
else return-1;
}
else if(a==')')return 1;
else if(a=='#') if(b=='#')return 0;else return -1;
else if(a=='+'||a=='-'){
if(b=='*'||b=='/'||b=='(')return -1;
else return 1;
}
else if(a=='*'||a=='/'){
if(b=='(')return -1;
else return 1;
}
}
double arithmetic(double a,char ch,double b){//算術部分
if(ch=='+')return (double)(a+b);
else if(ch=='-')return (double)(a-b);
else if(ch=='*')return (double)(a*b);
else if(ch=='/')return (double)(1.0*a/b);
}char ch;
int i=0;
void solve()
{
operators.push('#');
ch=getchar();
double t=0;
int num=0;
bool isHavePoint=false;
while(ch!='\n'||operators.top()!='#')//輸入的時候是輸入一個字符串,然後以換行結束
{
if(ch<='9'&&ch>='0'){
if(isHavePoint)
{
points.push(ch-'0');
ch=getchar();
continue;
}
num=0;
t=t*10+ch-'0';
ch=getchar();
continue;
}
if(num==0){//只能夠讓一個多位數的整數部分的數進棧一次,否則像22+22*3的例子裏邊,會有0多餘的進棧一次
num++;
operands.push(t);
// cout<<"即將進操作數棧的整數部分"<<":"<<t<<endl;
t=0;
}
if(ch=='.'){
isHavePoint=true;
ch=getchar();continue;
}
if(isHavePoint){
isHavePoint=false;
double tt=0;
while(!points.empty())
{
int a=points.top();
points.pop();
tt=(tt+a)*0.1;
}
double x=operands.top();
operands.pop();
x+=tt;
// cout<<"加上整數部分即將進操作數棧的小數部分的數的和"<<":"<<x<<endl;
operands.push(x);
}
if(Priority(operators.top(),ch)>0)
{
char op=operators.top();
operators.pop();
double a=operands.top();
operands.pop();
double b=operands.top();
operands.pop();
double result=arithmetic(b,op,a);
operands.push(result);
}
else if(Priority(operators.top(),ch)==0)
{
operators.pop();
ch=getchar();
}
else
{
operators.push(ch);
ch=getchar();
}
}
double result=operands.top();
while(!operands.empty())operands.pop();
while(!operators.empty())operators.pop();
cout<<result<<endl;
// getchar();//如果是以#作爲結束標誌的話就需要這個
}
int main()
{
while(true)
{
cout<<"請輸入一個算術表達式,以換行結束,注意不要輸入錯誤,否則會崩"<<endl;
solve();
}
}
//(23+4.5*2)/4 -----------------------------------------------------8
//22+22*3 -----------------------------------------------------88
//(22+3)*(33/3.0) ------------------------------------------------------275