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

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

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

输入格式:

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

输出格式:

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

输入样例:

1+2*10-10/2=

输出样例:

10

#include <stdio.h>

int main(void) {
    int result = 0, temp_int = 0;
    char temp_char, operate = '\0';

    while ((temp_char = getchar())!= '=') {
        if (temp_char >= '0'&&temp_char <= '9') {  //将每一个单独的数字组合成一个完整的运算数
            temp_int = 10 * temp_int + (temp_char - '0');
        }
        else {
            if (operate == '\0') {
                result += temp_int;  //将第一个运算数储存起来
            }
            else {
                if (operate == '+') {
                    result += temp_int;
                }
                else if (operate == '-') {
                    result -= temp_int;
                }
                else if (operate == '*') {
                    result *= temp_int;
                }
                else if (operate == '/') {
                    if (temp_int == 0) {  //0不可作为除数
                        printf("ERROR\n");

                        return 0;
                    }
                    result /= temp_int;
                }
                else {
                    printf("ERROR\n");  //遇到其他字符输出ERROR

                    return 0;
                }
            }
            temp_int = 0;
            operate = temp_char;
        }
    }  //读到等号后执行下列操作
    if (operate == '+') {
        result += temp_int;
    }
    else if (operate == '-') {
        result -= temp_int;
    }
    else if (operate == '*') {
        result *= temp_int;
    }
    else if (operate == '/') {
        if (temp_int == 0) {
            printf("ERROR\n");

            return 0;
        }
        result /= temp_int;
    }
    else if (operate == '\0') {  //最小等式,即只有数字,没有运算符的等式
        result += temp_int;
    }
    else {
        printf("ERROR\n");

        return 0;
    }
    printf("%d\n", result);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值