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;
}
运行结果显示如下
相关推荐
小李独爱秋1 天前
计算机网络经典问题透视:IP电话的通话质量与哪些因素有关?
服务器·开发语言·网络·网络协议·tcp/ip·计算机网络
sonadorje1 天前
矩阵方程求解
人工智能·算法·矩阵
BHXDML1 天前
第九章: STL 容器基础(C++)
开发语言·c++
董世昌411 天前
什么是暂时性死区?
开发语言·前端·javascript
茉莉玫瑰花茶1 天前
C++11 扩展 - 模板元编程
开发语言·c++
六毛的毛1 天前
hot100 python解法合集
开发语言·python
飞Link1 天前
预训练阶段中的模型自我提升、通用模型蒸馏和数据增强中的数据重构和非LLM驱动的数据增强
算法·重构·数据挖掘
实战项目1 天前
K-nearest算法在分类问题中的优化
算法·分类·数据挖掘
学嵌入式的小杨同学1 天前
【嵌入式 C 语言实战】手动实现字符串四大核心函数(strcpy/strcat/strlen/strcmp)
c语言·开发语言·前端·javascript·数据结构·数据库·算法
拾贰_C1 天前
[python | numpy] numpy& matplotib冲突
开发语言·python·numpy