UVa 1586 Molar mass (molecular weight)

Description bobo is a good boy who never satire high academic achievers, he recently indulged studying chemistry unable to extricate themselves. However calculate a relative molecular mass of molecules make her get bored, so she decided to ask you to write a program to help her calculate such a troublesome thing.

Known:
relative atomic mass of carbon is represented ①C 12.01, relative atomic mass of hydrogen is represented by H 1.008, relative atomic mass of oxygen is represented by O 16.00, relative atomic mass of nitrogen element represented by N 14.01 .
② relative molecular mass equal to a molecule composed of all the atoms of the molecule and the relative atomic mass: for example, the molecular weight of the formula C6H5OH molecules as: 1.008 + 12.01 * 6 * 5 = 94.108 + 1.008 + 16.00. A first input integer n, there are n representative of the next formula.

The next n lines, each line has a string formula. The data length of the string to ensure that not more than 90.
In the formula, C, H, O, N four kinds of letters only possible.
In the formula, each representing the letters may appear element numbers, these numbers are not smaller than 1 and not more than 100.
Output For each input and output of his relative molecular mass in a separate row, three decimal places (% .3lf). Sample input
4
C
C6H5OH
NH2CH2COOH
C12H22O11
Sample Output
12.010
94.108
75.070
342.296


解答:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char s='\n';
int read()
{
    s=getchar();
    if(s<'0'||s>'9') return 1;
    int x=0;
    while(s>='0'&&s<='9')
    {
        x=x*10+s-'0';
        s=getchar();
    }
    return x;
}
int main()
{
    double ans=0;
    int n;
    
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        while(s=='\n') s=getchar();
        while(s=='C'||s=='H'||s=='O'||s=='N')
        {
            if(s=='C') ans+=12.01*read();
            if(s=='H') ans+=1.008*read();
            if(s=='O') ans+=16*read();
            if(s=='N') ans+=14.01*read();
        }
        printf("%.3lf\n",ans);
        ans=0;
    }    
    return 0;
}

Guess you like

Origin www.cnblogs.com/satans/p/11108761.html