C语言计算相对分子质量
程序功能:
支持括号嵌套。
程序逻辑为原创。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
long long work(long long item);//主计算函数
long long getele(void);//提取相对原子质量
long long water(void);//添加结合水
char a[200];//分子式
int i = 0;//位置
int main(void) {
scanf("%s", &a);
long long ret = work(0);
if (ret % 10 == 0) {
printf("%lld\n", ret / 10);
}
else {
printf("%lld.5\n", ret / 10);
}
return 0;
}
long long work(long long item) {
if (a[i] >= 'A' && a[i] <= 'Z') {
return item + work(getele());
}
else if (a[i] == '_') {
i += 2;
int count = a[i] - 48;
while (a[i + 1] != '}') {
i++;
count = count * 10 + a[i] - 48;
}
item *= count;
i += 2;
return work(item);
}
else if (a[i] == '(') {
i++;
return item + work(work(0));
}
else if (a[i] == ')') {
i++;
return item;
}
if (a[i] == '~') {
return item + water();
}
else if (a[i] == '\0') {
return item;
}
}
long long water(void) {
i++;
if (a[i] == 'H') {
return 180;
}
else {
long long ret = 180;
int count = a[i] - 48;
while (a[i + 1] != 'H') {
i++;
count = count * 10 + a[i] - 48;
}
ret *= count;
return ret;
}
}
long long getele(void) {
if (a[i] == 'A')
{
i++;
if (a[i] == 'l') { i++; return 270; }
if (a[i] == 'g') { i++; return 1080; }
if (a[i] == 'u') { i++; return 1970; }
}
else if (a[i] == 'B') { i += 2; return 1370; }
else if (a[i] == 'C')
{
i++;
if (a[i] == 'a') { i++; return 400; }
if (a[i] == 'l') { i++; return 355; }
if (a[i] == 'u') { i++; return 640; }
return 120;
}
else if (a[i] == 'F')
{
i++;
if (a[i] == 'e') { i++; return 560; }
return 190;
}
else if (a[i] == 'H')
{
i++;
if (a[i] == 'f') { i++; return 1785; }
if (a[i] == 'g') { i++; return 2010; }
return 10;
}
else if (a[i] == 'I') { i++; return 1270; }
else if (a[i] == 'K') { i++; return 390; }
else if (a[i] == 'M')
{
i++;
if (a[i] == 'g') { i++; return 240; }
if (a[i] == 'n') { i++; return 550; }
}
else if (a[i] == 'N')
{
i++;
if (a[i] == 'a') { i++; return 230; }
return 140;
}
else if (a[i] == 'O') { i++; return 160; }
else if (a[i] == 'P')
{
i++;
if (a[i] == 't') { i++; return 1950; }
return 310;
}
else if (a[i] == 'S')
{
i++;
if (a[i] == 'i') { i++; return 280; }
return 320;
}
else if (a[i] == 'Z') { i += 2; return 650; }
}