【字符串、栈】string转double

stod函数

将string转为double

string t = s.substr(i, j - i);
double num = stod(t);

例题:货币单位换算

image

样例1
输入

2
20CNY53fen
53HKD87cents

输出

6432

说明:
20元53分+53港元87港分,换算成人民币分后汇总,为6432

样例2
输入

1
100CNY

输出

10000

说明:
100CNY转换后是10000fen,所以输出结果为10000

样例3
输入

1
3000fen

输出

3000

说明:
3000fen,结果就是3000

样例4
输入

1
123HKD

输出

10000

说明:
HKD与CNY的汇率关系是123:100,所以换算后,输出结果为10000


C++代码

#include <iostream>
#include <stack>

using namespace std;
using i64 = long long;

int n, sum;
stack<double> stk;

double get(string &s)
{
    for (int i = 0; i < s.size(); i++)
    {
        char x = s[i];
        if (isdigit(x))
        {
            int j = i;
            double num = 0;
            while (j < s.size() && isdigit(s[j])) j++;
            string t = s.substr(i, j - i);
            num = stod(t);
            stk.push(num);
            i = j - 1;
        }
        else if (isupper(x))
        {
            int j = i;
            string word;
            while (j < s.size() && isupper(s[j])) word += s[j++];
            double t = stk.top();
            stk.pop();
            if (word == "CNY") t *= 100;
            else if (word == "JPY") t = t / 1825 * 10000;
            else if (word == "HKD") t = t / 123 * 10000;
            else if (word == "EUR") t = t / 14 * 10000;
            else if (word == "GBP") t = t / 12 * 10000;
            stk.push(t);
            i = j - 1;
        }
        else if (islower(x))
        {
            int j = i;
            string word;
            while (j < s.size() && islower(s[j])) word += s[j++];
            double t = stk.top();
            stk.pop();
            if (word == "fen") t = t;
            else if (word == "cents") t = t / 123 * 100;
            else if (word == "sen") t = t / 1825 * 100;
            else if (word == "eurocents") t = t / 14 * 100;
            else if (word == "pence") t = t / 12 * 100;
            stk.push(t);
            i = j - 1;
        }
    }
    if (stk.size() > 1)
    {
        double b = stk.top();
        stk.pop();
        double a = stk.top();
        stk.pop();
        stk.push(a + b);
    }
    return stk.top();
}

int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n;
    while (n--)
    {
        string s;
        cin >> s;
        sum += (int)get(s);
    }
    cout << sum;
    return 0;
}
posted @   Tshaxz  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
Language: HTML
点击右上角即可分享
微信分享提示