Molar mass UVa1586

code:

//The second one
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#define maxn 110

char molar[5] = "CHON";
double weight_n[4]={ 12.01, 1.008, 16.00, 14.01};

//return the weight of the molecule(such as "CHON")
double weight(char c)
{
    int num = strchr(molar, c)-molar;
    return weight_n[num];
}

//return the digit of the number after the molecule.
int sum_n(int d[], int n) { int num = n-1; int sum = 0; for(int j =0 ; j < n; j++) { sum += d[j] * (int)pow(10,num--); } return sum; } int main() { int T(0); scanf("%d", &T); while(T--) { double sum(0); char a[maxn]; scanf("%s",a); int n = strlen(a); int flag = 1; //default: everytime puch back 1 element. int i = 0; for(; i < n; i += flag) { int num[maxn]; int index = 1; int number_n(1); int count = 0; if(isdigit(a[i+1])) //if there is number after the molecule, then count the number { while(isdigit(a[i+index])) { num[count] = (a[i+index]-48); index++; count++; } number_n = sum_n(num,index-1); flag = index; } else flag = 1; sum += weight(a[i])*number_n; //add the weight of molecules to the value sum; } printf("%.3f\n",sum); } return 0; }

 

  1.  第一部分是两个函数比较重要,一个是用来计算某个元素的摩尔质量;另一个是用来返回分子数目。
  2. 时刻要保持头脑清醒。
posted @ 2018-08-03 15:26  ClarkQian  阅读(121)  评论(0编辑  收藏  举报