分子量(UVa1586)
C++11代码如下:
1 #include<iostream> 2 #include<string.h> 3 #include<iomanip> 4 using namespace std; 5 #define maxn 85 6 char s[maxn]; 7 8 int main() { 9 int T; 10 cin >> T; 11 while (T--) { 12 int num_c = 0, num_h = 0, num_o = 0, num_n = 0; //分别记录各个化学元素的个数 13 float sum = 0.0; 14 cin >> s; 15 int n = strlen(s); 16 s[n] = 1; 17 for (int i = 0; i < n; i++) { 18 if (isalpha(s[i])) { //判断是否是字母 19 switch (s[i]) { 20 case 'C':if (isdigit(s[i + 1])) { //判断字母后面2位是否为数字 21 if (isdigit(s[i + 2])) num_c += (s[i + 1] - '0') * 10 + (s[i + 2] - '0'); 22 else num_c += (s[i + 1] - '0'); 23 } 24 else num_c++; break; 25 case 'H':if (isdigit(s[i + 1])) { 26 if (isdigit(s[i + 2])) num_h += (s[i + 1] - '0') * 10 + (s[i + 2] - '0'); 27 else num_h += (s[i + 1] - '0'); 28 } 29 else num_h++; break; 30 case 'O':if (isdigit(s[i + 1])) { 31 if (isdigit(s[i + 2])) num_o += (s[i + 1] - '0') * 10 + (s[i + 2] - '0'); 32 else num_o += (s[i + 1] - '0'); 33 } 34 else num_o++; break; 35 case 'N':if (isdigit(s[i + 1])) { 36 if (isdigit(s[i + 2])) num_n += (s[i + 1] - '0') * 10 + (s[i + 2] - '0'); 37 else num_n += (s[i + 1] - '0'); 38 } 39 else num_n++; break; 40 default:break; 41 } 42 } 43 else continue; //当前数组元素为数字,则直接进入下次循环 44 } 45 sum = 12.01*num_c + 1.008*num_h + 16.00*num_o + 14.01*num_n; 46 cout << fixed<<setprecision(3)<<sum << endl; //小数点后面保留三位数字 47 } 48 49 return 0; 50 }