算法经典入门竞赛 习题3.3 分子量

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define maxn 100
char s[maxn];
#define LOCAL

float returnm(char c)  //返回相对原子质量
{
	if (c == 'C')
		return 12.01;
	else if (c == 'H')
		return 1.008;
	else if (c == 'O')
		return 16.00;
	else
		return 14.01;
}

int main() {

#ifdef LOCAL
	freopen("input.txt", "r", stdin);
#endif 

	int n = 0;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%s", s);
		int len = strlen(s);
		float tot = 0;
		int j = 0;
		
		while (s[j] != '\0') 
		{			
			if (isalpha(s[j]))
			{
				char current = s[j];  //当前字母
				int weishu = 0;  //字母后面的数字个数
				int shu = 0;  //统计字母后面具体数值
				while (!isalpha(s[j + 1])&& s[j + 1]!='\0')  //第一次提交时没有加上这个s[j + 1]!='\0'
				{
					weishu++;
					j=j+1;
				}
				for (int k = 1; k <= weishu; k++)
				{
					shu = shu * 10 + (s[j + k - weishu]) - '0';  //每个元素的个数
				}
				tot = tot + shu*returnm(current);
				if (weishu == 0)  //如果字母后面没有数字
				{
					tot = tot + returnm(current);
				}
				j++;  //使得下一个字符为字母或者结束符
			}

		}
		printf("%.3f\n", tot);
	}
	return 0;
	
}

P57页。
先判断当前字符是否为字母,如果为字母,再判断其后是否为数字,然后把连续的数字字符转化成对应数字,current为当前字母字符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值