Regionals 2007 >> Asia - Seoul
问题链接:UVA1586 UVALive3900 Molar mass。基础练习题,用C++语言编写程序。
这个问题是根据分子式,求分子量。
原子量使用map表来存储,所以用C++来编程。
程序中,使用函数getchar()处理输入流,需要更高的编程技巧。
AC的C++语言程序如下:
/* UVA1586 UVALive3900 Molar mass */
#include <iostream>
#include <map>
#include <cstdio>
#include <cctype>
using namespace std;
map<char, double> aweight;
int main()
{
int t, count, mflag;
char c, molar;
double molarmass;
aweight['C'] = 12.01;
aweight['H'] = 1.008;
aweight['O'] = 16.00;
aweight['N'] = 14.01;
cin >> t;
getchar();
while(t--) {
molarmass = 0.0;
mflag = 0;
count = 0;
while((c=getchar()) != '\n' && c != EOF) {
if(isalpha(c)) {
if(mflag)
molarmass += ((count==0) ? 1 : count) * aweight[molar];
molar = c;
count = 0;
mflag = 1;
} else if(isdigit(c))
count = count * 10 + c - '0';
}
if(mflag)
molarmass += ((count==0) ? 1 : count) * aweight[molar];
// 输出结果
if(mflag)
printf("%.3f\n", molarmass);
}
return 0;
}