UVa 1586 Molar Mass
題意:
輸入一個分子式算出分子量題解:
輸入的分子式含有C、O、N、H四個元素
係數不超過99
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//UVa 1586 - Molar Mass | |
#include <cstdio> | |
#include <cstring> | |
#include <cctype> //用到isAlpha(), isDigit() | |
const double C = 12.010; | |
const double H = 1.008; | |
const double N = 14.010; | |
const double O = 16.000; | |
void add(char emt, int mole, double& mass) { | |
switch (emt) { | |
case 'C' : | |
mass += C*mole; | |
break; | |
case 'H': | |
mass += H*mole; | |
break; | |
case 'N': | |
mass += N*mole; | |
break; | |
case 'O': | |
mass += O*mole; | |
break; | |
default: | |
break; | |
} | |
} | |
int main() { | |
int t; | |
scanf("%d", &t); | |
for (int i = 0; i < t; ++i) { | |
char molar[85]; | |
double mass = 0; | |
scanf("%s", molar); | |
int len = strlen(molar); | |
for (int j = 0; j < len; ++j) { | |
char emt = molar[j]; | |
char p1 = molar[j+1], p2 = molar[j+2]; //係數十位與個位 | |
if(isalpha(emt)) { //先判斷是否為字母,false表示是係數 | |
if(isdigit(p1)) { //判斷是否有係數 | |
if(isdigit(p2)) { //再判斷是否為雙位係數 | |
add(emt, (p1 - '0')*10 + (p2 - '0'), mass); | |
j = j+2; //增加效率(可省略) | |
} else { | |
add(emt, p1 - '0', mass); | |
j++; | |
} | |
} else { //沒係數表示係數是1 | |
add(emt, 1, mass); | |
} | |
} | |
} | |
printf("%.3f\n", mass); | |
} | |
return 0; | |
} |
沒有留言:
張貼留言