问题描述:
给出一种物质的分子式(不带括号)求分子量。本题分子只包含4种原子,分别为C,H,O,N 分子量为分别为12.01,1.008,16.00,14.01(单位:g/mol)例如:C6H5OH 的分子量为 94.108g/mol
#include <stdio.h>
#include <string.h>
int main(){
char str[20];
int temp = 0,i = 0;
int num_c = 0,num_h = 0,num_o = 0,num_n = 0;
int temp_1 = 0;
double sum = 0.0;
while((str[temp] = getchar())!= '\n') temp++;
for(i = 0;i < temp+1;++i){
switch (str[i]) {
case 'C':
if(str[i+1] - '0' < 10){
i = i+1;
temp_1 = (str[i] - '0');
while(str[i+1] > ('0'-1)&&str[i+1] < ('9'+1)){
temp_1 = temp_1*10 + (str[i+1] - '0');
++i;
}
num_c = num_c + temp_1;
temp_1 = 0;
}
else ++num_c;
break;
case 'H':
if(str[i+1] > ('0'-1)&&str[i+1] < ('9'+1)){
i = i+1;
temp_1 = (str[i] - '0');
while(str[i+1] - '0' < 10){
temp_1 = temp_1*10 + (str[i+1] - '0');
++i;
}
num_h = num_h + temp_1;
temp_1 = 0;
}
else ++num_h;
break;
case 'O':
if(str[i+1] - '0' < 10){
i = i+1;
temp_1 = (str[i] - '0');
while(str[i+1] > ('0'-1)&&str[i+1] < ('9'+1)){
temp_1 = temp_1*10 + (str[i+1] - '0');
++i;
}
num_o = num_o + temp_1;
temp_1 = 0;
}
else ++num_o;
break;
case 'N':
if(str[i+1] > ('0'-1)&&str[i+1] < ('9'+1)){
i = i+1;
temp_1 = (str[i] - '0');
while(str[i+1] - '0' < 10){
temp_1 = temp_1*10 + (str[i+1] - '0');
++i;
}
num_n = num_n + temp_1;
temp_1 = 0;
}
else ++num_n;
break;
default:
break;
}
}
sum = num_c*12.01 + num_h*1.008 + num_n*14.01 + num_o*16.00;
printf("%.3lfg/mol",sum);
return 0;
}
作者:include4229
来源:CSDN
原文:https://blog.csdn.net/include4229/article/details/84328080
版权声明:本文为博主原创文章,转载请附上博文链接!