UVA-Molar Mass
An organic compoundis any member of a large class of chemical compounds whose molecules containcarbon. The molar mass of an organic compound is the mass of one mole of theorganic compound. The molar mass of an organic compound can be computed fromthe standard atomic weights of the elements.
When an organic compound is given as amolecular formula, Dr. CHON wants to find its molar mass. A molecular formula,such as C3H4O3 , identifies each constituent element by its chemical symbol andindicates the number of atoms of each element found in each discrete moleculeof that compound. If a molecule contains more than one atom of a particularelement, this quantity is indicated using a subscript after the chemicalsymbol.
In this problem, we assume that the molecularformula is represented by only four elements, C' (Carbon),
H’ (Hydrogen), O' (Oxygen), and
N’ (Nitrogen)without parentheses.
The following table shows that thestandard atomic weights for C',
H’, O', and
N’.
For example, the molar mass of a molecularformula C6H5OH is 94.108g/mol which is computed by 6 × (12.01 g/mol) + 6 × (1.008 g/mol) + 1 × (16.00g/mol).
Given a molecular formula, write a programto compute the molar mass of the formula.
InputYour program is to read from standardinput. The input consists of T testcases. The number of test cases T isgiven in the first line of the input. Each test case is given in a single line,which contains a molecular formula as a string. The chemical symbol is given bya capital letter and the length of the string is greater than 0 and 3900 - Molar mass1/2 less than 80. The quantity numbern which is represented after the chemical symbol would be omitted when thenumber is 1 (2 <= n <=99) .
OutputYour program is to write to standardoutput. Print exactly one line for each test case. The line should contain themolar mass of the given molecular formula.
Sample Input4
C
C6H5OH
NH2CH2COOH
Sample Output12.010
94.108
75.070
342.296
给定一个化学式,计算出这个元素的分子质量,那么要求解这个问题就需要统计这个化学式中各个元素的个数,再乘以其原子质量,得出最后的结果;
每当碰到一个数字的时候,就应当为数字前面的元素增加相应的数量;
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main()
{
int T;
scanf("%d", &T);
while(T--){
char s[85];
int sumC, sumH, sumO, sumN;
sumC = sumH = sumO = sumN = 0;
scanf("%s", s);
int len = strlen(s);
for(int i=0;i<len;i++){
if(s[i+1] == '\0' || isalpha(s[i+1])){
switch(s[i]){
case 'C':
sumC++;
break;
case 'H':
sumH++;
break;
case 'O':
sumO++;
break;
case 'N':
sumN++;
break;
default:
break;
}
}//if
else{
char cnt = s[i];
i++;
int fa = 0;
while(!isalpha(s[i]) && s[i]!='\0'){
fa *= 10;
fa += (s[i]-48);
i++;
}
i--;
switch(cnt){
case 'C':
sumC += fa;
break;
case 'H':
sumH += fa;
break;
case 'O':
sumO += fa;
break;
case 'N':
sumN += fa;
break;
default:
break;
}
}//else
}
float m;
m = sumC*12.01 + sumH*1.008 + sumN*14.01 + sumO*16.00;
printf("%.3f\n", m);
}//while
return 0;
}
版权声明
本文仅代表作者观点,不代表博信信息网立场。