实现计算器功能

本文介绍了如何使用C++编写一个支持基本算术运算的程序,包括加、减、乘、除操作,适用于初学者理解运算流程和编程基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.1point3acres.com/bbs/thread-12175-1-1.html


如何写出一个简单的4则运算的程序。
输入 " 1 -2*3 + 6/3" 
输出 -3

只用支持正数int的,+,-,*,/,不用写出()的情况








要注意的问题是,空格。。。。


可以直接用逆波兰式做,稍麻烦,用递归可以直接做


#include <iostream>
#include <cstdio>
using namespace std;
char c;
double num() {
        double ret = 0;
        while(c=getc(stdin)) {
                if(c >= '0' && c <= '9')
                        ret = ret * 10 + c-'0';
                else break;
        }
        double dec = 0.1;
        if(c=='.') {
                while(c=getc(stdin)) {
                        if(c >= '0' && c <= '9') {
                                ret += dec*(c-'0');
                                dec /= 10;
                        }
                        else break;
                }
        }
        return ret;
}
double calc_mul()//返回下一个数字或者返回后面乘除的值
{
        double ret = num();
        while(c=='*'||c=='/') {
                ret = c=='*'?ret*num():ret/num();
        }
        return ret;
}
double calc_add()
{
        double ret = calc_mul();
        while(c=='+'||c=='-') {
                ret = c=='+'?ret+calc_mul():ret-calc_mul();
        }
        return ret;
}
int main() {
        cout << calc_add() << endl;
        return 0;
}


int cal(int last, int idx ) {//idx指向当前的运算符,last指前一个数字
    if (idx >= n)
        return last;

    if (vt[idx] == "x")
        return cal(last * atoi(vt[idx+1].c_str()), idx + 2);
    if (vt[idx] == "/")
        return cal(last / atoi(vt[idx+1].c_str()), idx + 2);

    if (vt[idx] == "+")
    {
        if (idx + 2 >=N || vt[idx + 1] == "-" || vt[idx + 1] == "+")
            return cal(last + atoi(vt[idx+1].c_str()), idx +2);
        else 
            return last + cal(atoi(vt[idx+1].c_str()), idx +2);
    }
    //"-"同理
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值