用 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;
}