1586 - Molar massTime limit: 3.000 seconds |
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.InputYour 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.
Sample Input
4
C
C6H5OH
NH2CH2COOH
C12H22O11
Sample Output
12.010
94.108
75.070
342.296
解题:
-
定义4个数组,s放要输入的字符串,c放元素的原子质量(打表),遍历数组s,a放元素,b放数字;
-
注意每次循环后要把a、b清零,不然会有错误!!
-
并且注意只有数组b是int型,其他的都是浮点型(sum等),注意占位符格式!!
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
int t;
scanf("%d",&t);
int b[85];
char a[85],s[85];
// memset(s,0,sizeof(s));
double c[100];
c['C']=12.01;c['H']=1.008;c['O']=16.00;c['N']=14.01;
while(t--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
double sum=0;
scanf("%s",s);//printf("%s\n",s);
for(int i=0;i<strlen(s);i++)
{
// printf("s[%d]=%c\n",i,s[i]);
if(s[i]>='0'&&s[i]<='9')
b[i]=s[i]-'0';
else
a[i]=s[i];
}
for(int i=0;s[i];i++)
{
if(b[i+1]!=0)
{
// printf("b[%d]=%d\n",i+1,b[i+1]);
if(b[i+2]!=0)
{
// printf("%lf\n",c[a[i]]);
// printf("b[]=%d,%d\n",b[i+1],b[i+2]);
// printf("num=%lf\n",b[i+1]*10.0+b[i+2]);
// printf("%lf\n",c[a[i]]);
sum+=c[a[i]]*(b[i+1]*10.0+b[i+2]);
i++;
}
else {
// printf("%lf,%d\n",c[a[i]],b[i+1]);
sum+=c[a[i]]*b[i+1];
}
}
else sum+=c[a[i]];
}
printf("%.3lf\n",sum);
}
return 0;
}