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;
}
运行结果显示如下
相关推荐
若疆赤云online13 小时前
SpringGateway处理跨域
java·开发语言
Every exam must be13 小时前
10.27 JS学习12
开发语言·javascript·学习
雾里云山13 小时前
pgsql常用函数
java·开发语言·数据库·sql
星期天要睡觉13 小时前
提示词(Prompt)——链式思维提示词(Chain-of-Thought Prompting)在大模型中的调用(以 Qwen 模型为例)
开发语言·人工智能·python·语言模型·prompt
黑菜钟13 小时前
代码随想录第50天 | 图论 基础介绍(新篇章
算法·深度优先·图论
报错小能手13 小时前
计算机网络自顶向下方法16——应用层 因特网视频 HTTP流和DASH
开发语言·计算机网络·php
消失的旧时光-194313 小时前
Kotlin 协程实践:深入理解 SupervisorJob、CoroutineScope、Dispatcher 与取消机制
android·开发语言·kotlin
错把套路当深情13 小时前
Kotlin List扩展函数使用指南
开发语言·kotlin·list
草莓熊Lotso14 小时前
《算法闯关指南:优选算法--前缀和》--27.寻找数组的中心下标,28.除自身以外数组的乘积
开发语言·c++·算法·rpc
想不明白的过度思考者14 小时前
Rust——Trait 定义与实现:从抽象到实践的深度解析
开发语言·后端·rust