PTA 实验6-5 简单计算器

实验6-5 简单计算器

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

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

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

输入样例:
1+2*10-10/2=

输出样例:
10
思路:乍一看本题有点像中缀表达式求值,但是如果仔细观察题干会发现题目中有要求四种运算符的优先级相同这又意味着省去了运算符优先级判断的环节,来一个算一个就行,就省去了用栈。

#include <math.h>
#include <stdio.h>


int main(){
    
    
    char c;
    int result = 0,opnum; 
    scanf("%d",&result);
    c = getchar();
    while(c!='='){
    
    
        scanf("%d",&opnum);
        if(c == '+')
            result+=opnum;
        else if(c == '-')
            result-=opnum;
        else if(c == '*')
            result*=opnum;
        else if(c == '/')
        {
    
    
            if(opnum == 0){
    
    
                printf("ERROR");
                return 0;
            }else
                result/=opnum;
        }else{
    
    
            printf("ERROR");
                return 0;
        }
        c = getchar();
    }
    printf("%d",result);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Kilig___/article/details/128099114