算法入门经典
分子量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
double c[30] = {0,0,12.01,0,0,0,0,1.008,0,0,0,0,0,14.01,16.00,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int main()
{ //NCC79HNOH2HH4NH40C22H94H10N39C28NO33C22O4
int t;
scanf("%d", &t);
char str[100];
while(t--)
{
memset(str, 0, sizeof(str));
scanf("%s", str);
double sum = 0;
int i;
for(i = 0; i+2 < strlen(str); ++i)
{
double count = 0;
if(isalpha(str[i]))
{
if(isdigit(str[i+1]) && isdigit((str[i+2])))
{
count = (str[i+1] - '0') * 10 + (str[i+2]-'0');
sum = sum + count * (c[str[i] - 'A']);
++i;++i;
}
else if(isdigit(str[i+1]) && !isdigit(str[i+2]))
{
count = str[i+1]-'0';
sum = sum + count * c[str[i] - 'A'];
++i;
}
else
{
sum = sum + c[str[i] - 'A'];
}
}
}
if(i == strlen(str))
{
printf("%.3f\n", sum);
}
else if(i == strlen(str)-1)
{
sum = sum + c[str[i] - 'A'];
printf("%.3f\n", sum);
}
else
{
if(isalpha(str[i]) && isdigit(str[i+1]))
{
sum = sum + (str[i+1]-'0') * c[str[i] - 'A'];
printf("%.3f\n", sum);
}
else
{
for(;i < strlen(str); ++i)
{
sum = sum + c[str[i] - 'A'];
}
printf("%.3f\n", sum);
}
}
}
return 0;
}
中间排错浪费了我好多时间,不过我也学会了用codeblock调试。