3-2 「UVa1586」分子量:
给出一种物质的分子式(不带括号)求分子量。本题分子只包含4种原子,分别为C,H,O,N 分子量为分别为12.01,1.008,16.00,14.01(单位:g/mol)例如:C6H5OH 的分子量为 94.108g/mol
代码
#include<stdio.h>
#include<string.h>
#include<ctype.h>
double getweight(char x)
{
double m=0;
switch(x){
case 'C':m=12.01;break;
case 'H':m=1.008;break;
case 'O':m=16.00;break;
case 'N':m=14.01;break;
}
return m;
}
int main()
{
char x,s[20];
int t;
double sum=0;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
for(int i=0;i<strlen(s);i++){
if(isalpha(s[i])&&isdigit(s[i+1])&&isdigit(s[i+2]))
sum+=getweight(s[i])*((s[i+1]-'0')*10+s[i+2]-'0');
else if(isalpha(s[i])&&isdigit(s[i+1]))
sum+=getweight(s[i])*(s[i+1]-'0'); //char型的数字转化成int型要减去0
else if(isalpha(s[i])&&(!isdigit(s[i+1])))
sum+=getweight(s[i]);
}
printf("%.3f\n",sum);
sum=0;
}
return 0;
}
- 注意
- char型的数字转化成int型要减去0,而int型转化成char型要用sprintf