【UVa - 1586】

来源:互联网 发布:杭州乐其网络待遇 编辑:程序博客网 时间:2024/04/28 06:03
习题3-2 分子量(Molar Mass, ACM/ICPC Seoul 2007, UVa1586)
给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分
别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol)。例如,C6H5OH的

分子量为94.108g/mol。


Sample Input
4
C
C6H5OH
NH2CH2COOH
C12H22O11


Sample Output
12.010
94.108
75.070
342.296


#include<iostream>#include<cstdlib>#include<cstring>using namespace std;int main() {int n;char ele; double mol[] = {12.01, 0, 0, 0, 0, 1.008, 0, 0, 0, 0, 0, 14.01, 16.00};//存储原子量 cin >> n;while(n--) {string s;int len;int times;double count = 0;cin >> s;len = s.length();for(int i = 0; i < len; i++) {if(isalpha(s[i])) {//如果是字母 ele = s[i];if(i == len-1 || isalpha(s[i+1])) {//原子数量为1 times = 1;count += mol[ele-'C']*times;}}else if(isdigit(s[i])) {//如果是数字 if(isdigit(s[i+1])) {//原子数量为两位数 times = (s[i] - '0')*10 + s[i+1] - '0';count += mol[ele-'C']*times;i++;//两位数需要再跑一位 }else {//原子数量为一位数 times = s[i] - '0';count += mol[ele-'C']*times;}}}printf("%.3lf\n", count);}return 0;}


0 0