solution
- 测试点4:直接给出数字,即零个运算符的情况
#include<iostream>
#include<string>
#include<map>
#include<cmath>
using namespace std;
int main(){string s, ans = "";map<string, int> mp = {{"ling", 0}, {"yi", 1}, {"er", 2}, {"san", 3}, {"si", 4}, {"wu", 5}, {"liu", 6}, {"qi", 7}, {"ba", 8}, {"jiu", 9}};for(int i = 0; i < 11; i++){cin >> s;if(s.size() == 1) ans += s;else if(s.substr(0, 4) == "sqrt") ans += to_string((int)sqrt(atoi(s.substr(4, s.size() - 4).c_str())));else if(isalpha(s[0])) ans += to_string(mp[s]);else{int n = 0, m = 0, j, d;char com;for(j = 0; j < s.size() && isdigit(s[j]); j++){n = s[j] - '0' + n * 10;}com = s[j];for(j = j + 1; j < s.size(); j++){m = s[j] - '0' + m * 10;} if(com == '+') d = n + m;else if(com == '-') d = n - m;else if(com == '*') d = n * m;else if(com == '/') d = n / m;else if(com == '%') d = n % m;else d = pow(n, m);ans += to_string(d);}}cout << ans;return 0;
}
或者
#include<iostream>
#include<string>
#include<map>
#include<cmath>
using namespace std;
int main(){string s;map<string, int> mp = {{"ling", 0}, {"yi", 1}, {"er", 2}, {"san", 3}, {"si", 4}, {"wu", 5}, {"liu", 6}, {"qi", 7}, {"ba", 8}, {"jiu", 9}};for(int i = 0; i < 11; i++){cin >> s;if(s.size() == 1) cout << s;else if(s.substr(0, 4) == "sqrt") cout << sqrt(atoi(s.substr(4, s.size() - 4).c_str()));else if(isalpha(s[0])) cout << mp[s];else{int n = 0, m = 0, j, d;char com;for(j = 0; j < s.size() && isdigit(s[j]); j++){n = s[j] - '0' + n * 10;}com = s[j];for(j = j + 1; j < s.size(); j++){m = s[j] - '0' + m * 10;} if(com == '+') d = n + m;else if(com == '-') d = n - m;else if(com == '*') d = n * m;else if(com == '/') d = n / m;else if(com == '%') d = n % m;else d = pow(n, m);cout << d;}}return 0;
}