UVA-1586 - Molar mass
网上看了挺多解法都是先读字符串来处理的,下面我们给出一种单个字符处理的解法。
#include<stdio.h> #include<string.h> #include<ctype.h> double Mass[]= {12.01,1.008,16.00,14.01}; char Atomic[]= {'C','H','O','N'}; int MassCount[4]; int main() { int t; scanf("%d",&t); getchar(); while(t--) { char c=getchar();//ch表示当前输入的字符,c表示前一个元素,先处理第一个字符 char ch = c; int Count=0; memset(MassCount,0,sizeof(MassCount)); while(ch=getchar()) { if(isdigit(ch))//如果这是一个数字,就累加在Count中 { Count*=10; Count+=ch-'0'; } else//当不是数字时 { if(!Count){Count=1;}//如果Count为0,说明是两个元素连在一起,中间没数字,那么前一个元素相应地在其计数数组中累加1 int i; for(i=0; i<4&&Atomic[i]!=c; i++);//找出其在计数数组中的位置 MassCount[i]+=Count; Count = 0; if(ch=='\n')//不把判断写在while后面,因为这样如果是单个元素的话,由于我们在循环前就读入了,那么循环开始再读只能是换行符,就进不来循环了 { break; } c = ch;//元素更新 } } double sum=0; for(int i=0; i<4; i++) { sum+=MassCount[i]*Mass[i]; } printf("%.3f\n",sum); } return 0; }