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;
}
运行结果显示如下
相关推荐
快手技术14 分钟前
快手提出端到端生成式搜索框架 OneSearch,让搜索“一步到位”!
算法
感哥1 小时前
C++ 多重继承
c++
博笙困了1 小时前
C++提高编程 4.0
c++
扑克中的黑桃A1 小时前
[C语言]第三章-数据类型&变量
c++
感哥2 小时前
C++ std::string
c++
感哥18 小时前
C++ 面向对象
c++
CoovallyAIHub20 小时前
中科大DSAI Lab团队多篇论文入选ICCV 2025,推动三维视觉与泛化感知技术突破
深度学习·算法·计算机视觉
沐怡旸20 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
NAGNIP21 小时前
Serverless 架构下的大模型框架落地实践
算法·架构
moonlifesudo21 小时前
半开区间和开区间的两个二分模版
算法