题解:
改题目要求写出分子式,求出他的mol,由于没有括号,基本都是原题模拟就ok了
我的想法每次把上一个记录下来,然后最后搞最后一个。注意点是两个字母相邻的时候,num为0;因此要分开判断
#include <cstdio> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <map> #include <cctype> using namespace std; map<char,double> mol; void init(){ mol['C'] = 12.01; mol['H'] = 1.008; mol['O'] = 16.00; mol['N'] = 14.01; } int main() { //freopen("in.txt","r",stdin); //freopen("output.txt","w",stdout); init(); int n; scanf("%d",&n); for(int i = 0; i < n; i++){ string str; cin >> str; double sum = 0; int num = 0; //保存数字 char tmp = str[0]; //保存上一个字母 int len = str.size(); for(int i = 1; i < len; i++){ if(isalpha(str[i])){ if(!num) sum += mol[tmp]; else sum += mol[tmp]*num; num = 0; tmp = str[i]; }else{ if(num) num = num*10+str[i]-'0'; else num = str[i] - '0'; } } if(isalpha(str[len-1])) sum += mol[tmp]; else sum += mol[tmp]*num; printf("%.3f\n",sum); } return 0; }