Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case is given in a single line, which contains a molecular formula as a string. The chemical symbol is given by a capital letter and the length of the string is greater than 0 and less than 80. The quantity number n which is represented after the chemical symbol would be omitted when the number is 1 (2n99) .
Your program is to write to standard output. Print exactly one line for each test case. The line should contain the molar mass of the given molecular formula.
4 C C6H5OH NH2CH2COOH C12H22O11
12.010 94.108 75.070 342.296#include <iostream> #include <string.h> using namespace std; #define maxn 100 float molar(char c) { if(c == 'C') return 12.01; else if(c == 'H') return 1.008; else if(c == 'O') return 16.00; else if(c == 'N') return 14.01; } int main() { int T; cin >> T; while(T--) { char s[maxn]; float total = 0; scanf("%s", s); for(int i = 0; i < strlen(s); i++) { if(s[i] == 'C' || s[i] == 'H' || s[i] == 'O' || s[i] == 'N') total += molar(s[i]); else { if((s[i] <= '9' && s[i] >= '1') && (s[i+1] <='0' || s[i+1] > '9')) total += molar(s[i-1]) * (s[i]-'0'-1);//注意ASCII码中数字与正常数字,应减去'0' else { total += molar(s[i-1]) * ((s[i]-'0')*10 + (s[i+1]-'0'-1)); //cout << ((s[i]-'0')*10 + (s[i+1]-'0'-1)) << endl; i++; } } } printf("%.3f\n", total); } return 0; }