PAT 1118 如需挪车请致电

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;
}
相关推荐
alphaTao1 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
Interview Aid1122 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
顶点多余11 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
罗西的思考12 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha601613 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘14 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
维克兜率天16 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
AI情绪识别开源17 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶17 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法
不会就选b18 小时前
算法日常・每日刷题--<BFS拓扑排序>4
算法