As the title :( UVa not registered, or use vjudge)
https://vjudge.net/problem/UVA-1586
Comment on the details inside. Original.
Essay in that for a combination of elements (element number +), only three possibilities:
1, a single element
2, the elements and a digit
3, elements, and a two-digit number
No. Because the account of the problems set n <= 99, shows that the number of only two digits. Respectively judgment can be.
/* Copyright 2019 AlexanderZ.Tang Molar_mass.cpp For UVa 1586 https://cnblogs.cn/nowonder */ #include <stdio.h> #include <string.h> #include <ctype.h> const int num[] = {0,1,2,3,4,5,6,7,8,9}; //使用数组将字符数字转为数字,ch - '0'即为该数字的下标 char s[80]; //储存字符串,n<=80 double get_mass(char ch) { //获得对应字符的分子量 if (ch=='C') return 12.01; if (ch=='H') return 1.008; if (ch=='O') return 16.00; if (ch=='N') return 14.01; } int main() { int T; double sum; scanf("%d",&T); while (T--) //计数器 { sum = 0; scanf("%s",s); int len = strlen(s); if (len < 2) //对于单个字符,直接输出,否则造成溢出 { printf("%.3lf\n",get_mass(s[0])); continue; } for (int i=0;i<len-2;i++) //防止溢出,从0到len-3 { if (!isalpha(s[i])) continue; //数字跳过 if (!isalpha(s[i+1])) //一个元素带一个数字(个位数) { if (!isalpha(s[i+2])) //一个元素带两个数字(十位数) { sum += get_mass(s[i]) * (num[s[i+1] - '0'] * 10 + num[s[i+2] - '0']); } else { sum += get_mass(s[i]) * num[s[i+1] - '0']; } } else //单独元素,直接算 { sum += get_mass(s[i]); } } //字符串s中剩下两个字符 //如果全是数字直接跳 if (isalpha(s[len-2])) { if (!isalpha(s[len-1])) //元素带个位数 { sum += get_mass(s[len-2]) * num[s[len-1] - '0']; } else //单独元素 { sum += get_mass(s[len-2]); } } if (isalpha(s[len-1])) sum += get_mass(s[len-1]); //最后一个字符 printf("%.3lf\n",sum); //输出 } return 0; }