分子量
给出一个物质的分子式(不带括号),求分子量。本题中的分子只包含4种原子,分别为C,H,O,N,原子量分别为12.01,1.008,16.00,14.01(单位:g/mol)。例如,C6H5OH的分子量为94.08g/mol。
#include <iostream>
#include <string>
using namespace std;
int main()
{
char s[100];
double result = 0;
scanf_s("%s", s, sizeof(s));
for (int i = 0; i < strlen(s); i++)
{
if (isdigit(s[i + 1]))
{
if (s[i] == 'C')
{
result += 12.01*(s[i + 1] - '0');
i++;
}
else if (s[i] == 'H')
{
result += 1.008*(s[i + 1] - '0');
i++;
}
else if (s[i] == 'O')
{
result += 16.00*(s[i + 1] - '0');
i++;
}
else if (s[i] == 'N')
{
result += 14.01*(s[i + 1] - '0');
i++;
}
}
else
{
if (s[i] == 'C')
{
result += 12.01;
}
else if (s[i] == 'H')
{
result += 1.008;
}
else if (s[i] == 'O')
{
result += 16.00;
}
else if (s[i] == 'N')
{
result += 14.01;
}
}
}
cout << result << endl;
}