我使用了C++的map,用key来存储运算符号,value存储一个特定数字,然后用switch来表示运算结果。
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <map> using namespace std; int main(void) { int a, b; float result; string c; map<string, int> mymap; mymap.insert(make_pair("+", 1)); mymap.insert(make_pair("-", 2)); mymap.insert(make_pair("*", 3)); mymap.insert(make_pair("/", 4)); mymap.insert(make_pair("%", 5)); cin >> a >> c >> b; map<string, int>::iterator iter; iter = mymap.find(c); if (iter != mymap.end()) { switch (iter->second) { case 1: result = a + b; break; case 2: result = a - b; break; case 3: result = a * b; break; case 4: result = a / b; break; case 5: result = a % b; break; default: break; } cout << result; } else { cout << "ERROR"; } return 0; }
网上的C语言方法也挺不错,记下来
#include <stdio.h> #include <math.h> int main() { int n1, n2; char a; scanf("%d %c %d", &n1, &a, &n2); if (a == '-') { printf("%d", n1 - n2); } else if(a == '+') { printf("%d", n1 + n2); } else if(a == '*') { printf("%d", n1 * n2); } else if (a == '/') { printf("%d", n1 / n2); } else if(a == '%') { printf("%d", n1 % n2); } else { printf("ERROR"); } return 0; }