题目具体描述见:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=830&page=show_problem&problem=4461

C++11代码如下:

 #include<iostream>
#include<string.h>
#include<iomanip>
using namespace std;
#define maxn 85
char s[maxn]; int main() {
int T;
cin >> T;
while (T--) {
int num_c = , num_h = , num_o = , num_n = ; //分别记录各个化学元素的个数
float sum = 0.0;
cin >> s;
int n = strlen(s);
s[n] = ;
for (int i = ; i < n; i++) {
if (isalpha(s[i])) { //判断是否是字母
switch (s[i]) {
case 'C':if (isdigit(s[i + ])) { //判断字母后面2位是否为数字
if (isdigit(s[i + ])) num_c += (s[i + ] - '') * + (s[i + ] - '');
else num_c += (s[i + ] - '');
}
else num_c++; break;
case 'H':if (isdigit(s[i + ])) {
if (isdigit(s[i + ])) num_h += (s[i + ] - '') * + (s[i + ] - '');
else num_h += (s[i + ] - '');
}
else num_h++; break;
case 'O':if (isdigit(s[i + ])) {
if (isdigit(s[i + ])) num_o += (s[i + ] - '') * + (s[i + ] - '');
else num_o += (s[i + ] - '');
}
else num_o++; break;
case 'N':if (isdigit(s[i + ])) {
if (isdigit(s[i + ])) num_n += (s[i + ] - '') * + (s[i + ] - '');
else num_n += (s[i + ] - '');
}
else num_n++; break;
default:break;
}
}
else continue; //当前数组元素为数字,则直接进入下次循环
}
sum = 12.01*num_c + 1.008*num_h + 16.00*num_o + 14.01*num_n;
cout << fixed<<setprecision()<<sum << endl; //小数点后面保留三位数字
} return ;
}
05-11 18:08