刷题第八题:Molar mass

tech2025-11-15  3

题目链接:https://vjudge.net/problem/UVA-1586 题解:字符串处理:需要单独考虑只有一个元素的情况,以及最后一位加不上,需要单独加 代码:

#include<iostream> #include<cstring> #include<string> #include<iomanip> #define maxn 110 #define C 12.01 #define O 16.0 #define H 1.008 #define N 14.01 using namespace std; int main() { char s[maxn]; int len;//字符串长度 int n;//输入字符串个数 double ans;//ans int fl;//原子的个数 cin>>n; while(n--) { int numH=0; int numO=0; int numN=0; int numC=0; fl=0; ans=0; char ch; cin>>s; int len=strlen(s); ch=s[0]; if(s[1]==0) { if(ch=='O') numO+=1; else if(ch=='C') numC+=1; else if(ch=='H') numH+=1; else numN+=1; } for(int i=1; s[i]!=0; i++) { if(isdigit(s[i])) { fl*=10; fl+=(s[i]-'0'); } if(!isdigit(s[i])) { if(!fl) fl=1; if(ch=='O') numO+=fl; else if(ch=='C') numC+=fl; else if(ch=='H') numH+=fl; else numN+=fl; fl=0; ch=s[i]; } } if(s[1]!=0) { if(isdigit(s[len-1])) { if(ch=='O') numO+=fl; else if(ch=='C') numC+=fl; else if(ch=='H') numH+=fl; else numN+=fl; } else { if(ch=='O') numO+=1; else if(ch=='C') numC+=1; else if(ch=='H') numH+=1; else numN+=1; } } cout<<fixed<<setprecision(3)<<numH*H+numN*N+numO*O+numC*C<<endl; } return 0; }
最新回复(0)