最近在做一些数学题(其实是表达式求值)的时候,有一些计算题,自己懒得算,于是自己做了一个程序(其实是一道题)
请注意,算式中只能有“(”、 “)”、“0~9”、“+”、“-”、“*”、“/”、“^”(乘方)
上代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
char ch1[1000010];
char ch[1000010];
stack<int> num;
stack<char> str;
bool f=false;
int len;
int last;
int cmp(char x,char y) {
if(x=='('&&y==')') return 0;
if(x=='('||y=='(') return -1;
if(y==')') return +1;
if(x=='+'||x=='-') return (y=='+'||y=='-') ? +1 : -1;
if(x=='*'||x=='/') return (y=='*'||y=='/'||y=='+'||y=='-') ? +1 : -1;
return 1;
}
int sum(int a,int b,char c) {
if(c=='+') return a+b;
if(c=='-') return a-b;
if(c=='*') return a*b;
if(c=='/') return a/b;
if(c=='^') return pow(a,b);
}
signed main() {
X:
if(last) printf("上一个算式:"),cout<<ch1<<"="<<num.top()<<endl;
printf("请输入算式:");
if(!num.empty()) num.pop();
if(!str.empty()) str.pop();
f=false;
len=0;
cin>>ch1;
ch[++len]='(';
for(int i=0; i<=strlen(ch1); i++) {
if((ch1[i]=='+'||ch1[i]=='-')&&(!i||ch1[i-1]=='(')) ch[++len]='0';
if(ch1[i]=='('&&ch1[i-1]==')') ch[++len]='*';
ch[++len]=ch1[i];
}
ch[len]=')';
str.push('(');
for(int i=1; i<=len; i++) {
int ans=0;
if(ch[i]>='0'&&ch[i]<='9') {
while(ch[i]>='0'&&ch[i]<='9') {
ans=ans*10+ch[i]-'0';
i++;
}
num.push(ans);
}
while(1) {
int can=cmp(str.top(),ch[i]);
if(can==-1) {
str.push(ch[i]);
break;
}
if(can==0) {
str.pop();
break;
}
int x=num.top();
num.pop();
int y=num.top();
num.pop();
char c=str.top();
num.push(sum(y,x,c));
str.pop();
}
}
cout<<"答案:"<<num.top()<<endl;
last=num.top();
system("pause");
system("cls");
goto X;
return 0;
}
谢谢观看!!!
祝大家2023年新年快乐,万事如意,兔飞猛进,大展宏兔!!!