习题3-2 分子量(Molar Mass)

来源:互联网 发布:芒果网络考试系统 3.9 编辑:程序博客网 时间:2024/04/29 12:22
#include <iostream>#include <stdio.h>#include <string.h>#include <ctype.h>double gmol(char ch) {    if(ch=='C') return 12.01;    else if(ch=='H') return 1.008;    else if(ch=='O') return 16.00;    else if(ch=='N') return 14.01;}int num(char ch) {    return (ch-'0');}using namespace std;int main() {    char s[1001];    int len,i,n,t,j,l,k;    double sum;    while(scanf("%d",&k)!=EOF) {        for(l=1; l<=k; l++) {            while(scanf("%s",s)!=EOF) {                len=strlen(s);                sum=0;                for(n=1,i=len-1; i>=0;) {                    if(!isalpha(s[i])) {                        t=1,n=0;                        for(j=i; !isalpha(s[j])&&j>0; j--) {                            n+=(num(s[j])*t);                            t*=10;                        }                        i=j;                    } else {                        sum+=(gmol(s[i])*n);                        for(j=i-1; isalpha(s[j])&&j>=0; j--) {                            sum+=gmol(s[j]);                        }                        i=j;                    }                }                printf("%.3f\n",sum);            }        }    }    return 0;}
/*写了蛮久 云里雾里 . 自定义了2个函数 gmol取原子量 num取数量 从数组最后len-1开始取元素 isalpha判断是否是字母(头文件 ctype.h) n为转化后的数量 ×原子量 相加*/

0 0
原创粉丝点击