平台:
UVa Online Judge
題號:
1586 - Molar mass
題目連結:
題目說明:
给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol)。例如,C6H5OH的分子量为94.108g/mol。
範例輸入:
4
C
C6H5OH
NH2CH2COOH
C12H22O11
範例輸出:
12.010
94.108
75.070
342.296
解題方法:
用while循环取数字,组成n位数。
程式碼:
1 #include <cstdio> 2 #include <cctype> 3 #include <cstring> 4 5 const int MAXN = 85; 6 double q['Z'] = { 0 }; 7 8 void setStandard() { 9 q['C'] = 12.01; 10 q['H'] = 1.008; 11 q['O'] = 16.00; 12 q['N'] = 14.01; 13 } 14 15 int main() { 16 setStandard(); 17 int T = 0; 18 scanf("%d", &T); 19 while (T--) { 20 char formula[MAXN] = ""; 21 scanf("%s", formula); 22 int num = 0; 23 double sta = 0.0, sum = 0.0; 24 for (int i = 0; i < strlen(formula); ) { 25 if (isalpha(formula[i])) { 26 sta = q[formula[i++]]; 27 while (isdigit(formula[i])) { 28 num = num * 10 + formula[i] - '0'; 29 i++; 30 } 31 if (num == 0) { 32 num = 1; 33 } 34 sum += sta * num; 35 num = 0; 36 } 37 38 } 39 printf("%.3lf\n", sum); 40 } 41 }
Happy Life Forever