Problem 3-2 Molecular Weight of Introduction to Algorithmic Competition

Keywords: Programming

Problem 3-2 Molecular Weight of Introduction to Algorithmic Competition

The molecular formula of a substance (without parentheses) is given to calculate its molecular weight. The formula in this question contains only four kinds of atoms, namely C, H, O, N. Atomic theory is 12.01, 1.008, 16.00, 14.01 (unit: g/mol). For example, the molecular weight of C6H5OH is 94.108 g/mol.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int C=0,H=0,O=0,N=0;
		char s[110];
		double sum=0;
		scanf("%s",s);
		int psum=0;
		for(int i=0;i<strlen(s);i++)
		{
			if(s[i]=='C')
			{
				if(s[i+1]>='1'&&s[i+1]<='9')
				{
					psum=s[i+1]-'0';
					for(int j=i+1;!isalpha(s[j])&&j<strlen(s)-1;j++)
					{
						if(!isalpha(s[j+1])&&j+1<strlen(s))
						    psum=psum*10+(s[j+1]-'0');						
					}
					C+=psum;
				}
				else C++;
			}
				if(s[i]=='H')
			{
				if(s[i+1]>='1'&&s[i+1]<='9')
				{
					psum=s[i+1]-'0';
					for(int j=i+1;!isalpha(s[j])&&j<strlen(s)-1;j++)
					{
						if(!isalpha(s[j+1])&&j+1<strlen(s))
						    psum=psum*10+(s[j+1]-'0');					
					}	
					H+=psum;
				}
				else H++;
			}
				if(s[i]=='O')
			{
				if(s[i+1]>='1'&&s[i+1]<='9')
				{
					psum=s[i+1]-'0';
					for(int j=i+1;!isalpha(s[j])&&j<strlen(s)-1;j++)
					{
						if(!isalpha(s[j+1])&&j+1<strlen(s))
						    psum=psum*10+(s[j+1]-'0');					
					}	
					O+=psum;
				}
				else O++;
			}
				if(s[i]=='N')
			{
				if(s[i+1]>='1'&&s[i+1]<='9')
				{
					psum=s[i+1]-'0';
					for(int j=i+1;!isalpha(s[j])&&j<strlen(s)-1;j++)
					{
						if(!isalpha(s[j+1])&&j+1<strlen(s))
						    psum=psum*10+(s[j+1]-'0');						
					}
					N+=psum;
				}
				else N++;
			}
		}
		sum=C*12.01+H*1.008+O*16.00+N*14.01;
		printf("%.3lf\n",sum);
	}
 } 

If there is no number after the letter, record the number of letters + 1; if there is a number, record the value of the number before the next letter, plus the value of that number.
(ミルクティーがおいしい)

Posted by freejellyfish on Wed, 23 Jan 2019 04:57:13 -0800