UVA1586 Molar mass【基础题】

An organic compound is any member of a large class of chemicalcompounds whose molecules contain carbon. The molarmass of an organic compound is the mass of one mole of theorganic compound. The molar mass of an organic compoundcan be computed from the standard atomic weights of theelements.

  When an organic compound is given as a molecular formula,Dr. CHON wants to find its molar mass. A molecularformula, such as C3H4O3, identifies each constituent element byits chemical symbol and indicates the number of atoms of eachelement found in each discrete molecule of that compound. Ifa molecule contains more than one atom of a particular element,this quantity is indicated using a subscript after the chemical symbol.

  In this problem, we assume that the molecular formula is represented by only four elements, ‘C’(Carbon), ‘H’ (Hydrogen), ‘O’ (Oxygen), and ‘N’ (Nitrogen) without parentheses.

  The following table shows that the standard atomic weights for ‘C’, ‘H’, ‘O’, and ‘N’.


  For example, the molar mass of a molecular formula C6H5OH is 94.108 g/mol which is computed by6 × (12.01 g/mol) + 6 × (1.008 g/mol) + 1 × (16.00 g/mol).

  Given a molecular formula, write a program to compute the molar mass of the formula.

Input

Your program is to read from standard input. The input consists of T test cases. The number of testcases T is given in the first line of the input. Each test case is given in a single line, which containsa molecular formula as a string. The chemical symbol is given by a capital letter and the length ofthe string is greater than 0 and less than 80. The quantity number n which is represented after thechemical symbol would be omitted when the number is 1 (2 ≤ n ≤ 99).

Output

Your program is to write to standard output. Print exactly one line for each test case. The line shouldcontain the molar mass of the given molecular formula.

扫描二维码关注公众号,回复: 897364 查看本文章

Sample Input

4

CC6H5OH

NH2CH2COOH

C12H22O11

Sample Output

12.010

94.108

75.070

342.296

题意:给你C H O N的相对原子质量,让你求分子的相对分子质量。
分析关键在于处理C22这样的,一个元素后边跟着两个数字的。
AC代码:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define maxn 80+5
const double a[]={0,0,12.01,0,0,0,0,1.008,0,0,0,0,0,14.01,16.00};  
int main(void)
{
	char s[maxn];
	int t;
	int i;
	int len;
	scanf("%d",&t);
	while(t--)
	{
		double sum = 0;
		scanf("%s",s);
		len = strlen(s);
		for(i = 0; i < len; i++)
		{
			if(isalpha(s[i]))
				sum += a[s[i]-'A'];
			if(isdigit(s[i]))
			{
				int count = 0;
				if(isdigit(s[i+1]))
					count += (s[i]-'0')*10+(s[i+1]-'0');
				else
					count += s[i]-'0';
				sum += a[s[i-1]-'A']*(count-1);
			}
		}
		printf("%.3f\n",sum); 
	}
} 

猜你喜欢

转载自blog.csdn.net/wxd1233/article/details/80343979