一个拥有“+”“-”“*”“/”“^”五个功能的计算器

#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<math.h>
#define eps 1e-8
using namespace std;
bool illegal;
char s[10005];
int cur=0,n;
string OP="+-*/^";
bool isOper(char c){
    for(int i=0;i<OP.length();i++)
        if(OP[i]==c)return true;
    return false;
}
int sgn(double x){
    if(fabs(x)<=eps)return 0;
    return x>0?1:-1;
}
char next_char(){
    for(;s[cur]==' '||s[cur]=='\t';cur++);
    return cur<n?s[cur]:EOF;
}
int get_priority(char ch){
    if(ch=='^')return 3;
    else if(ch=='*'||ch=='/')return 2;
    return 1;
}
double calc(double a,char op,double b){
    if(op=='+')return a+b;
    else if(op=='-')return a-b;
    else if(op=='*')return a*b;
    else if(op=='/'){
        if(sgn(b)==0){
            illegal=true;
            return 1.0;
        }else return a/b;
    }else if(op=='^')return pow(a,b);
}
double P();
double calc_exp(int p){
    double a=P();
    while(isOper(next_char())&&get_priority(next_char())>=p){
        char op=next_char();
        cur++;
        a=calc(a,op,calc_exp(get_priority(op)+1));
    }
    return a;
}
char temp[1005];
double P(){
    if(next_char()=='-'){
        cur++;
        return -P();
    }else if(next_char()=='+'){
        cur++;
        return P();
    }else if(next_char()=='('){
        cur++;
        double r=calc_exp(0);
        if(next_char()==')')cur++;
        return r;
    }else{
        int len=0;
        while(next_char()>='0'&&next_char()<='9'||next_char()=='.'){
            temp[len++]=next_char();
            cur++;
        }
        temp[len]=0;
        double x;
        sscanf(temp,"%lf",&x);
        return x;
    }
}
int main(){
	printf("请输入一个由+ - * / 数字 括号构成的表达式:\n");
    while(gets(s)){
    	printf("请输入一个由+ - * / 数字 括号构成的表达式:\n");
        n=strlen(s);
        cur=0;
        illegal=false;
        double res=calc_exp(0);
        if(illegal)
            printf("The teacher is so lazy!\n");
        else printf("%.8f\n",res);
    }
    return 0;
}

(如有改进建议请提出~)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值