算法竞赛入门——习题3-2 分子量

习题3-2 分子量

UVa1585

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
const char s0[5] = "CHON";
const double num[4] = {12.01, 1.008, 16.00, 14.01};

void f(const char *s){
	int n = strlen(s);
	double sum = 0;			 //sum用于储存分子量  
	double t = 0;            //t用于储存原子量 
	int tag;                 //tag标记是字母还是数字 
	int i = 0;
	while(s[i]!='\0'){
		t = 0;
		if(isalpha(s[i])){    //isalpha判断是否为字母,只涉及字母与数字,字母为1,数字为0 
			tag = 1;          
			if(s[i]=='C') t = num[0];
			else if(s[i]=='H') t = num[1];
			else if(s[i]=='O') t = num[2];
			else if(s[i]=='N') t = num[3];
			sum += t;         //先将一个原子量大小加到sum中,如果后续没有数字,则无需变动 
		}					  // 若后续有数字n,则加完n个后再减去一个原子量,避免重复加 
		else tag = 0; 
		i++;
		int x = i;
		if(x == n) break;
		double nums = 0;      //nums用于累加某个元素的总原子量,相隔元素分别计算 
		do{
			if(isalpha(s[i])) tag = 1;
			else {
				tag = 0;
				i++;	
			}
		}while(!tag && i<n);
		for(int j = x; j < i; j++){
			nums += (s[j]-'0')*pow(10,i-j-1)*t;
		}
		if(nums) sum += nums - t;
	}
	printf("%.3f\n", sum);
}

int main(){
	int T;
	scanf("%d", &T);
	while(T--){
		char s[100];
		scanf("%s", s);
		f(s);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值