您的位置:首页 > 其它

UVA 1586 - Molar mass

2017-09-06 15:02 381 查看
题目大意:输入字符串代表分子式,求相对分子质量,只包含C、H、N、O。

解题思路:遇到字母,判断后一位是否为数字,如果为,读入数字。

ac代码:
#include <iostream>
#include <cstring>
#include <map>
using namespace std;
map <char, double>ma;
int main()
{
int n, len, cnt;
double sum, temp;
char a[106];
scanf("%d", &n);
ma['C'] = 12.01, ma['H'] = 1.008;
ma['O'] = 16, ma['N'] = 14.01;
while (n--){
scanf("%s", a);
len = strlen(a);
sum = 0;
for (int i=0; i<len; i++)
if (isalpha(a[i])){
temp = ma[a[i]];
cnt = 0;
while (a[i+1] >= '0' && a[i+1] <= '9'){
cnt = cnt*10 + a[i+1] - '0';
i++;
}
if (cnt)
sum += temp * cnt;
else
sum += temp;
}
printf("%.3lf\n", sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: