C++ //练习 14.44 编写一个简单的桌面计算器使其能处理二元运算。

C++ Primer(第5版) 练习 14.44

练习 14.44 编写一个简单的桌面计算器使其能处理二元运算。

环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp 复制代码
/*************************************************************************
	> File Name: ex14.44.cpp
	> Author: 
	> Mail: 
	> Created Time: Tue 09 Jul 2024 10:37:09 AM CST
 ************************************************************************/

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
#include<map>
using namespace std;

int add(int a, int b){
    return a + b;
}

auto mod = [](int a, int b){ return a % b; };

struct divide{
    int operator()(int a, int b){
        return a / b;
    }
};


int main(){
    map<string, function<int(int, int)>> binops = {
        {"+", add},
        {"-", std::minus<int>()},
        {"/", divide()},
        {"*", [](int a, int b){ return a * b; }},
        {"%", mod}
    };

    int a, b;
    cout<<"Enter a and b: ";
    cin>>a>>b;
    cout<<"a + b = "<<binops["+"](a, b)<<endl;
    cout<<"a - b = "<<binops["-"](a, b)<<endl;
    cout<<"a * b = "<<binops["*"](a, b)<<endl;
    cout<<"a / b = "<<binops["/"](a, b)<<endl;
    cout<<"a % b = "<<binops["%"](a, b)<<endl;

    return 0;
}
运行结果显示如下
相关推荐
杨筱毅38 分钟前
【优秀三方库研读】【C++基础知识】odygrd/quill -- 折叠表达式
c++·三方库研读
东阳马生架构1 小时前
Sentinel源码—8.限流算法和设计模式总结二
算法·设计模式·sentinel
曹牧1 小时前
Java 调用webservice接口输出xml自动转义
java·开发语言·javascript
老饼讲解-BP神经网络2 小时前
一篇入门之-评分卡变量分箱(卡方分箱、决策树分箱、KS分箱等)实操例子
算法·决策树·机器学习
hjjdebug2 小时前
c++中的enum变量 和 constexpr说明符
c++·enum·constexpr
何其有幸.2 小时前
实验6-3 使用函数求特殊a串数列和(PTA|C语言)
c语言·数据结构·算法
pyengine2 小时前
基于pandoc的MarkDown格式与word相互转换小工具开发(pyqt5)
开发语言·python·qt·word
不会计算机的捞地2 小时前
【数据结构入门训练DAY-24】美国大选
数据结构·算法
YuSun_WK2 小时前
配置MambaIRv2: Attentive State Space Restoration的环境
开发语言·python
Nick_zcy2 小时前
开发基于python的商品推荐系统,前端框架和后端框架的选择比较
开发语言·python·前端框架·flask·fastapi