C++练习

发布时间:2024年01月18日

C++练习

用 C++ 写一个四则运算

// 常规写法
#include <iostream>

using namespace std;

int add(int a, int b)
{
    return a + b;
}

int min(int a, int b)
{
    return a - b;
}

int mul(int a, int b)
{
    return a * b;
}

double divi(int a, int b)
{
    return (double)(a / b);
}

int main()
{
    int a = 0;
    int b = 0;
    char ch;
    while(1)
    {
        cout << "请输入数字:" << endl;
        cin >> a;
        cin >> b;
        cout << "请输入运算符+、-、*、/:" << endl;
        cin >> ch;
        switch(ch)
        {
        case ('+'):
            cout << add(a, b) << endl;
            break;
        case ('-'):
            cout << min(a, b) << endl;
            break;
        case ('*'):
            cout << mul(a, b) << endl;
            break;
        case ('/'):
            cout << divi(a, b) << endl;
            break;
        }
    }
    return 0;
}
// 采用之前所学的 Lambda 表达式
#include <iostream>

using namespace std;

int main()
{
    int a = 0;
    int b = 0;
    char ch;

    auto add = [](int a,int b) -> int{return a + b;};
    auto min = [](int a,int b) -> int{return a - b;};
    auto mul = [](int a,int b) -> int{return a * b;};
    auto divi = [](int a,int b) -> double{return (double)(a / b);};

    while(1)
    {
        cout << "请输入数字:" << endl;
        cin >> a;
        cin >> b;
        cout << "请输入运算符+、-、*、/:" << endl;
        cin >> ch;
        switch(ch)
        {
        case ('+'):
            cout << add(a, b) << endl;
            break;
        case ('-'):
            cout << min(a, b) << endl;
            break;
        case ('*'):
            cout << mul(a, b) << endl;
            break;
        case ('/'):
            cout << divi(a, b) << endl;
            break;
        }
    }
    return 0;
}

文章来源:https://blog.csdn.net/weixin_47642634/article/details/135658883
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。