UVa 1586 - Molar mass

本文介绍了一种使用C++编程语言解析化学分子式的算法,并计算其摩尔质量的方法。通过建立原子权重数组并遍历输入的化学式字符串,该算法能够识别出化学元素并计算总值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

识别化学式,然后计算总值

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 using namespace std;
 5 double a[5]={0,12.01,1.008,16.00,14.01};
 6 char s[105];
 7 int t,len,cnt;
 8 double ans,tmp;
 9 void fuc(){
10     ans=0; cnt=1;
11     for(int i=0;i<len;i++){
12         if(s[i]=='C') tmp=a[1];
13         else if(s[i]=='H') tmp=a[2];
14         else if(s[i]=='O') tmp=a[3];
15         else if(s[i]=='N') tmp=a[4];
16         else {
17             cnt*=(s[i]-'0');
18             while(s[i+1]<='9'&&s[i+1]>='0'){
19                 i++;
20                 cnt*=10;
21                 cnt+=(s[i]-'0');
22             }
23         }
24         if(s[i+1]>'9'||s[i+1]<'0'){
25             ans+=tmp*cnt;
26             cnt=1;
27         }
28     }
29 }
30 int main(){
31     scanf("%d",&t);
32     while(t--){
33         scanf("%s",s);
34         len=strlen(s);
35         fuc();
36         printf("%.3lf\n",ans);
37     }
38 }

 

转载于:https://www.cnblogs.com/nicetomeetu/p/5275763.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值