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;
}
运行结果显示如下
相关推荐
Filotimo_1 天前
EntityGraph的概念
java·开发语言·数据库·oracle
wregjru1 天前
【读书笔记】Effective C++ 条款1~2 核心编程准则
java·开发语言·c++
CodeAmaz1 天前
一致性哈希与Redis哈希槽详解
redis·算法·哈希算法
lingran__1 天前
C语言自定义类型详解 (1.1w字版)
c语言·开发语言
POLITE31 天前
Leetcode 42.接雨水 JavaScript (Day 3)
javascript·算法·leetcode
Tim_101 天前
【算法专题训练】36、前缀树路径和
算法
好易学·数据结构1 天前
可视化图解算法76:最大子数组和
数据结构·算法·leetcode·面试·动态规划·力扣·笔试
村口曹大爷1 天前
JDK 24 正式发布:性能压轴,为下一代 LTS 铺平道路
java·开发语言
副露のmagic1 天前
更弱智的算法学习 day13
学习·算法
青岛少儿编程-王老师1 天前
CCF编程能力等级认证GESP—C++1级—20251227
java·c++·算法