算法竞赛入门经典第二版课后习题 3-2分子量
# include <iostream>
# include <cstdlib>
# include <memory.h>
# include <cctype>
using namespace std;
const char name[] = "CHON";
double fweight[] = {12.01, 1.008, 16.00, 14.01};
int main()
{
char c[5];
string s;
cin>>s;
double sum = 0.0,weight = 0.0;
int num = 0;
for(int i = 0; i < s.size(); i++)
{
if(isalpha(s[i]))
{
for(int j = 0; j < 4; j++)
{
if(s[i] == name[j])
{
weight = fweight[j];
break;
}
}
num = 0;
if(isalpha(s[i+1]) || i+1 == s.size())
sum += weight;
else
{
for(int k = i+1; k < s.size() && isdigit(s[k]); k++)
{
c[num] = s[k];
num++;
}
cout<<"atof(c) = "<<atof(c)<<endl;
sum += atof(c)*weight;
}
memset(c,'\0',sizeof(c));
}
else
continue;
}
cout<<sum;
return 0;
}