分子量(Molar Mass UVa1586)
Posted Intro1997
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分子量(Molar Mass UVa1586)相关的知识,希望对你有一定的参考价值。
题目来自刘汝佳的《算法竞赛入门经典(第二版)》
题目描述:
我的代码:
#include<iostream> #include<cstring> #include <iomanip> using namespace std; #define C 12.01 #define H 1.008 #define O 16.00 #define N 14.01 int main() { int i, k; char enter[1000]; cin >> k; while (k--) { cin >> enter; double tot = 0.0; int num = 0, j; double ans = 0; for (i = 0; i < strlen(enter); i++) { ans = 0; switch (enter[i]) { case \'C\': num = 0; if (enter[i + 1] <= \'9\' && enter[i + 1] >= \'0\') { i++; while (enter[i] <= \'9\' && enter[i] >= \'0\') { if (num == 0) num = i; i++; } for (j = i; num < j; num++) ans += ((double)(enter[num] - \'0\') * pow(10, j - num - 1)); tot += ans * C; i--; } else tot += C; break; case \'H\': num = 0; if (enter[i + 1] <= \'9\' && enter[i + 1] >= \'0\') { i++; while (enter[i] <= \'9\' && enter[i] >= \'0\') { if (num == 0) num = i; i++; } for (j = i; num < j; num++) ans += ((double)(enter[num] - \'0\') * pow(10, j - num - 1)); tot += ans * H; i--; } else tot += H; break; case \'O\': num = 0; if (enter[i + 1] <= \'9\' && enter[i + 1] >= \'0\') { i++; while (enter[i] <= \'9\' && enter[i] >= \'0\') { if (num == 0) num = i; i++; } for (j = i; num < j; num++) ans += ((double)(enter[num] - \'0\') * pow(10, j - num - 1)); tot += ans * O; i--; } else tot += O; break; case \'N\': num = 0; if (enter[i + 1] <= \'9\' && enter[i + 1] >= \'0\') { i++; while (enter[i] <= \'9\' && enter[i] >= \'0\') { if (num == 0) num = i; i++; } for (j = i; num < j; num++) ans += ((double)(enter[num] - \'0\') * pow(10, j - num - 1)); tot += ans * N; i--; } else tot += N; break; } } cout << setiosflags(ios::fixed) << setprecision(3) << tot << "g/mol" << endl; } return 0; }
Sample Input
4
C
C6H5OH
NH2CH2COOH
C12H22O11
Sample Output
12.010
94.108
75.070
342.296
水题,但是有陷阱,所以特地放了上来╮(╯▽╰)╭,求大神们更好的代码~
以上是关于分子量(Molar Mass UVa1586)的主要内容,如果未能解决你的问题,请参考以下文章