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;
}
运行结果显示如下
相关推荐
大闲在人2 小时前
C、C++区别还是蛮大的
c语言·开发语言·c++
Cosmoshhhyyy3 小时前
《Effective Java》解读第39条:注解优先于命名模式
java·开发语言
追随者永远是胜利者3 小时前
(LeetCode-Hot100)20. 有效的括号
java·算法·leetcode·职场和发展·go
清水白石0084 小时前
Python 纯函数编程:从理念到实战的完整指南
开发语言·python
掘根4 小时前
【C++STL】平衡二叉树(AVL树)
开发语言·数据结构·c++
叫我一声阿雷吧4 小时前
JS实现响应式导航栏(移动端汉堡菜单)|适配多端+无缝交互【附完整源码】
开发语言·javascript·交互
瓦特what?4 小时前
快 速 排 序
数据结构·算法·排序算法
前路不黑暗@4 小时前
Java项目:Java脚手架项目的文件服务(八)
java·开发语言·spring boot·学习·spring cloud·docker·maven
niuniudengdeng4 小时前
基于时序上下文编码的端到端无文本依赖语音分词模型
人工智能·数学·算法·概率论