制作一个简易计算器

最近在做一些数学题(其实是表达式求值)的时候,有一些计算题,自己懒得算,于是自己做了一个程序(其实是一道题)

请注意,算式中只能有“(”、 “)”、“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年新年快乐,万事如意,兔飞猛进,大展宏兔!!!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值