刷题第八题:Molar mass

题目链接:https://vjudge.net/problem/UVA-1586
题解:字符串处理:需要单独考虑只有一个元素的情况,以及最后一位加不上,需要单独加
代码:

#include<iostream>
#include<cstring>
#include<string>
#include<iomanip>
#define maxn 110
#define C 12.01
#define O 16.0
#define H 1.008
#define N 14.01
using namespace std;
int main()
{
    char s[maxn];
    int len;//字符串长度
    int n;//输入字符串个数
    double ans;//ans
    int fl;//原子的个数
    cin>>n;
    while(n--)
    {
        int numH=0;
        int numO=0;
        int numN=0;
        int numC=0;
        fl=0;
        ans=0;
        char ch;
        cin>>s;
        int len=strlen(s);
        ch=s[0];
        if(s[1]==0)
        {
            if(ch=='O')
                numO+=1;
            else if(ch=='C')
                numC+=1;
            else if(ch=='H')
                numH+=1;
            else
                numN+=1;
        }
        for(int i=1; s[i]!=0; i++)
        {
            if(isdigit(s[i]))
            {
                fl*=10;
                fl+=(s[i]-'0');
            }
            if(!isdigit(s[i]))
            {
                if(!fl)
                    fl=1;
                if(ch=='O')
                    numO+=fl;
                else if(ch=='C')
                    numC+=fl;
                else if(ch=='H')
                    numH+=fl;
                else
                    numN+=fl;
                fl=0;
                ch=s[i];
            }
        }
        if(s[1]!=0)
        {
            if(isdigit(s[len-1]))
            {
                if(ch=='O')
                    numO+=fl;
                else if(ch=='C')
                    numC+=fl;
                else if(ch=='H')
                    numH+=fl;
                else
                    numN+=fl;
            }
            else
            {
                if(ch=='O')
                    numO+=1;
                else if(ch=='C')
                    numC+=1;
                else if(ch=='H')
                    numH+=1;
                else
                    numN+=1;
            }
        }
        cout<<fixed<<setprecision(3)<<numH*H+numN*N+numO*O+numC*C<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值