给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol),输入分子式,输出分子量,保留三位小数。
头文件
#include<ctype.h>
isupper()这个方法是判断是否为大写字母,isdigit()这个方法判定是否为数字。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <ctype.h>
int main()
{
double W[256];
W['C'] = 12.01, W['H'] = 1.008, W['O'] = 16.0, W['N'] = 14.01; //存入CHON的值
char ans[256],a;
double sum = 0;
int tot = 0; //计数器
scanf("%s", ans);
int len = strlen(ans);
for (int i = 0; i < len; i++)
{
a = ans[i]; //记录首个字母;
if (isdigit(ans[i+1])) //判断下个是否为数字
{
while (isdigit(ans[i + 1]))
{
tot = tot * 10 + (ans[i + 1] - '0'); //记录数字
i++;
}
sum += W[a] * tot;
tot = 0;
}
else
{
sum += W[a]; //单个字母的情况
}
}
printf("%.3lf\n", sum);
return 0;
}