分子量。
给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol)。例如,C6H5OH的分子量为94.108g/mol。
写的时候事直接按照刘汝佳的算法入门经典(第2版)的第57页习题3-2,没打开UVaOJ,只写大致实现方法
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define maxn 85
int main()
{
char s[maxn];
scanf("%s",s);
int len=strlen(s);
double sum=0;
int temp=1;
for(int i=len-1; i>=0; i--)//采用倒序读入,会使程序简单些,我这么觉得
{
if(s[i]=='C')
{
sum+=12.01*temp;
temp=1;
}
else if(s[i]=='H')
{
sum+=1.008*temp;
temp=1;
}
else if(s[i]=='O')
{
sum+=16.00*temp;
temp=1;
}
else if(s[i]=='N')
{
sum+=14.01*temp;
temp=1;
}
else{
temp=s[i]-'0';//数字情况
}
}
printf("%.3f",sum);
}