题目大意就是给一个只含有C/H/O/N四个字母的分子式,求分子量。跟着题目意思来进行模拟就好了。重点与难点在于如何处理字母后一位数字以上的数字。写得略显繁杂。
#include <iostream> #include <string> #include <cstdio> #include <cstring> #define maxn 1000000+10 #include <ctype.h> using namespace std ; double mol[4] = {12.01,1.008,16.00,14.01} ; /// C6H5OH /// CO2 /// C12 H22 O11 int main(){ int t ; std::cin >> t ; while ( t -- ){ string str ; cin >> str ; int len = str.size() ; double num_C = 0 , num_H = 0 , num_O = 0 , num_N = 0 ; for ( int i = 0 ; i < len ; i ++ ){ if ( i < len-1 ){ if (isalpha(str[i])){ if ( str[i] == ‘C‘ && !isdigit(str[i+1]) ) num_C ++ ; else if ( str[i] == ‘C‘ && isdigit(str[i+1]) ) { double temp_C = 0 ; int j = i+1 ; while ( isdigit(str[j]) ){ temp_C = temp_C*10 + (str[j]-‘0‘) ; j ++ ; } num_C += temp_C ; } if ( str[i] == ‘H‘ && !isdigit(str[i+1]) ) num_H ++ ; else if ( str[i] == ‘H‘ && isdigit(str[i+1]) ) { double temp_H = 0 ; int j = i+1 ; while ( isdigit(str[j]) ){ temp_H = temp_H*10 + (str[j]-‘0‘) ; j ++ ; } num_H += temp_H ; } if ( str[i] == ‘O‘ && !isdigit(str[i+1]) ) num_O ++ ; else if ( str[i] == ‘O‘ && isdigit(str[i+1]) ) { double temp_O = 0 ; int j = i+1 ; while ( isdigit(str[j]) ){ temp_O = temp_O*10 + (str[j]-‘0‘) ; j ++ ; } num_O += temp_O ; } if ( str[i] == ‘N‘ && !isdigit(str[i+1]) ) num_N ++ ; else if ( str[i] == ‘N‘ && isdigit(str[i+1]) ) { double temp_N = 0 ; int j = i+1 ; while ( isdigit(str[j]) ){ temp_N = temp_N*10 + (str[j]-‘0‘) ; j ++ ; } num_N += temp_N ; } } } else{ if ( str[i] == ‘C‘ ) num_C ++ ; if ( str[i] == ‘H‘ ) num_H ++ ; if ( str[i] == ‘O‘ ) num_O ++ ; if ( str[i] == ‘N‘ ) num_N ++ ; } } // cout << num_C << " " << num_H << " " << num_O << " " << num_N << endl ; double ans = num_C*mol[0] + num_H*mol[1] + num_O*mol[2] + num_N*mol[3] ; printf("%.3lf\n" , ans) ; } return 0 ; }
原文地址:https://www.cnblogs.com/Cantredo/p/9353652.html
时间: 2024-11-12 09:29:31