pta 7-19 简单计算器 (20分)

模拟简单运算器的工作。假设计算器只能进行加减乘除运算,运算数和结果都是整数,四种运算符的优先级相同,按从左到右的顺序计算。

输入格式:

输入在一行中给出一个四则运算算式,没有空格,且至少有一个操作数。遇等号”=”说明输入结束。

输出格式:

在一行中输出算式的运算结果,或者如果除法分母为0或有非法运算符,则输出错误信息“ERROR”。

输入样例:

1+2*10-10/2=

输出样例:

10
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
string str;
int x,y;
char ch;
int main(){
    cin>>x;
    while(1){
        cin>>ch;
        if(ch=='='){
            cout<<x;
            break;
        }else if(ch=='+'){
            cin>>y;
            x+=y;
        }else if(ch=='-'){
            cin>>y;
            x-=y;
        }else if(ch=='/'){
            cin>>y;
            if(y==0){
                printf("ERROR");
                return 0;
            }
            x/=y;
        }else if(ch=='*'){
            cin>>y;
            x*=y;
        }else{
            printf("ERROR");
            return 0;
        }
    }
    return 0;
}
发布了32 篇原创文章 · 获赞 7 · 访问量 819

猜你喜欢

转载自blog.csdn.net/Young_Naive/article/details/104027715