思路,其实还是切分单词,只不过这里的单词,变成了数字。代码如下。
1 #include <stdio.h>
2 #include <string.h>
3 #include <ctype.h>
4 #define MAXN 100
5
6 char buf[MAXN] = {0};
7 double t[26] = {0};
8 int readInt(char * buf, int i, int *num);
9 int main() {
10
11 int n;
12 int ch, num;
13 t['C'-'A'] = 12.01, t['H'-'A'] = 1.008;
14 t['O' - 'A'] = 16.00, t['N' - 'A'] = 14.01;
15 scanf("%d", &n);
16
17 while (n > 0) {
18
19 // 1.输入数据
20 scanf("%s", buf);
21 int len = strlen(buf);
22 double sum = 0.0;
23 int i = 0;
24
25 // 2.计算
26 for (;;) {
27
28 for (; buf[i]&&isalpha(buf[i]); i++) {
29 sum += t[buf[i] - 'A'];
30 }
31 if (i >= len) break;
32
33 // 2.1[i, e)为整数范围,num为整数值
34 int e,num;
35 e = readInt(buf, i, &num);
36 sum += t[buf[i - 1] - 'A'] * (num - 1);
37 i = e;
38 }
39
40 // 3.输出结果
41 printf("%.3f\n", sum);
42 n--;
43 }
44
45 return 0;
46 }
47
48 // 如果没有找到则返回i
49 int readInt(char * buf, int i, int *num) {
50 int sum = 0;
51 int j;
52 for (j = i; buf[j] && isdigit(buf[j]); j++) {
53 sum *= 10;
54 sum += buf[j] - '0';
55 }
56 *num = sum;
57 return j;
58
59 }
by sixleaves