如需挪车请致电-模拟-easy


7-3 如需挪车请致电 (20分)

phone.jpg

上图转自新浪微博。车主用一系列简单计算给出了自己的电话号码,即:

2/2=1、3+2=5、√9=3、√9=3、0%=0、叁=3、5?2=3、9/3=3、1×3=3、23=8、8/2=4,最后得到的电话号码就是 153 3033 3384。

本题就请你写个程序自动完成电话号码的转换,以帮助那些不会计算的人。

输入格式:

输入用 11 行依次给出 11 位数字的计算公式,每个公式占一行。这里仅考虑以下几种运算:加(+)、减(-)、乘(*)、除(/)、取余(%,注意这不是上图中的百分比)、开平方根号(sqrt)、指数(^)和文字(即 0 到 9 的全小写汉语拼音,如 ling 表示 0)。运算符与运算数之间无空格,运算数保证是不超过 1000 的非负整数。题目保证每个计算至多只有 1 个运算符,结果都是 1 位整数。

输出格式:

在一行中给出电话号码,数字间不要空格。

输入样例:

2/2
3+2
sqrt9
sqrt9
6%2
san
5-2
9/3
1*3
2^3
8/2

输出样例:

15330333384
#include 
using namespace std;

map mp{
    {"ling", 0},
    {"yi", 1},
    {"er", 2},
    {"san", 3},
    {"si", 4},
    {"wu", 5},
    {"liu", 6},
    {"qi", 7},
    {"ba", 8},
    {"jiu", 9}
};

int to_int(string s) {
    if (mp.count(s)) {
        return mp[s];
    }
    else {
        int res = 0;
        for (int i = 0; i <= s.size() - 1; ++i)
            res += (s[i] - '0') * pow(10.0, s.size() - i - 1);
        return res;
    }
}

int func(string s) {
    if (s.find("sqrt") != string::npos) {
        return sqrt(to_int(s.substr(4)));
    }
    for (char oper : string("+-*/%^")) { //借鉴一下
        int oper_pos = s.find(oper);
        if (oper_pos != string::npos) {
            int a = to_int(s.substr(0, oper_pos));
            int b = to_int(s.substr(oper_pos + 1));
            if (oper == '+') return a + b;
            if (oper == '-') return a - b;
            if (oper == '*') return a * b;
            if (oper == '/') return a / b;
            if (oper == '%') return a % b;
            if (oper == '^') return pow(a, b);
        }
    }
    return to_int(s);
}

int main() {
    for (int i = 0; i < 11; i++) {
        string s;
        cin >> s;
        cout << func(s) << endl;
    }
}

转https://www.cnblogs.com/Kanoon/p/13633931.html#commentform