UVA-1586 Molar mass

原题地址

B - Molar mass

解题思路

难题在于要在字符串中读取连续的数字。我用的是字符串的拼接,并且用到了stoi函数。

看网上题解,其实可以直接计算。

参考代码

自己写的~

#include<bits/stdc++.h>
using namespace std;
#define _for(i, a, b) for(int i = (a); i < (b); ++i)
#define _rep(i, a, b) for(int i = (a); i <= (b); ++i)
#define pb push_back
#define LOCAL  //提交的时候一定要记得注释掉这句话
#define maxn 100010
#define INF 0x3f3f3f3f
int readint() {
    
    
    int x; scanf("%d", &x); return x;
}
int gen[maxn];  //标记数i的生成数是gen[i]
int main() {
    
    
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);  //可以把结果直接打印出来看
#endif
    map<char, double> mp = {
    
    {
    
    'C', 12.01}, {
    
    'H', 1.008}, {
    
    'O', 16.00}, {
    
    'N', 14.01}};
    int t;
    scanf("%d", &t);
    char c;
    getchar();
    string s, cnt = "";
    while (t--) {
    
    
        cin >> s;
        int next;
        double sum = 0;
        _for(i, 0, s.size()) {
    
    
            next = i + 1;
            cnt = "";
            while (next < s.size() && isdigit(s[next])) {
    
    
                cnt += s[next];
                next++;
            }
            sum += mp[s[i]] * (cnt == "" ? 1 : (stoi(cnt)));
            i = next - 1;
        }
        printf("%.3f\n", sum);
    }
    return 0;
}

也记录一下不用字符串的写法:

//不用字符串的写法
int q = 0;
while (isdigit(s[next])) {
    
    
    q *= 10;
    q += s[next] - '0';
    next++;
}

猜你喜欢

转载自blog.csdn.net/Encore47/article/details/109288223