1118 如需挪车请致电 - PAT (Basic Level) Practice (中文) (pintia.cn)
我刚开始是这样写的:
js
#include<bits/stdc++.h>
using namespace std;
map<string, int> m = { {"ling",0},{"yi",1},{"er",2},{"san",3},{"si",4},{"wu",5},{"liu",6},{"qi",7},{"ba",8},{"jiu",9} };
int main()
{
int n = 11;
string s;
for (int i = 0; i < n; i++)
{
cin >> s;
if (s.size() == 1)cout << s;
else if (s[0] == 's' && s[1] == 'q')cout << sqrt(stoi(s.substr(4)));
else if (m.count(s))cout << m[s];
else
{
if (s[1] == '+')
{
cout << s[0] - '0' + s[2] - '0';
}
else if (s[1] == '-')
{
cout << s[0] - '0' - s[2] - '0';
}
else if (s[1] == '*')
{
cout << s[0] - '0' * s[2] - '0';
}
else if (s[1] == '/')
{
cout << s[0] - '0' / s[2] - '0';
}
else if (s[1] == '%')
{
cout << s[0] - '0' % s[2] - '0';
}
else if (s[1] == '^')
{
cout << pow(s[0] - '0', s[2] - '0');
}
}
}
return 0;
}
但是这样会出现,因为题目说了运算数是1-9999的数字,不一定是一位数,如果像这样写死的话只能计算一位数字的运算。
要改成下面这样的
js
#include <iostream>
#include <map>
#include <cmath>
#include <string>
using namespace std;
string s, c;
map<string,int> A = {{"ling", 0}, {"yi", 1}, {"er", 2}, {"san", 3}, {"si", 4}, {"wu", 5}, {"liu", 6}, {"qi", 7}, {"ba", 8}, {"jiu", 9}};
int main() {
for (int I = 0; I < 11; I++) {
cin >> s;
if (s.size() == 1) cout << s;
else if (s[0] == 's' && s[1] == 'q') cout << sqrt(stoi(s.substr(4)));
else if (A.count(s)) cout << A[s];
else {
int a = 0, b = 0, i = 0;
while(i < s.size() && isdigit(s[i])) a = a * 10 + s[i++] - '0';
c = s[i++];
while(i < s.size()) b = b * 10 + s[i++] - '0';
if (c == "+") cout << a + b;
else if (c == "-") cout << a - b;
else if (c == "*") cout << a * b;
else if (c == "/") cout << a / b;
else if (c == "%") cout << a % b;
else cout << pow(a, b);
}
}
return 0;
}