UVa1586(c++實現)

#include<iostream>
#include<iomanip>
#include<string>
#include<cstdlib>
using namespace std;

const double C = 12.010;
const double H = 1.008;
const double O = 16.000;
const double N = 14.010;

int main() {
	char tempC = ' ';
	int tempN = 0;
	int i;
	setiosflags(ios::fixed);
	double sum = 0;
	cin >> i;
	for (; i > 0; i--) {
		string s;
		cin >> s;
		sum = 0;
		tempN = 0;
		tempC = ' ';
		for (size_t j = 0; j < s.size(); j++) {
			if ('0' < s[j] && s[j]<= '9') {
				tempN = tempN * 10 + (s[j] - '0');
			}
			else {
				if (tempN != 0) {
					switch (tempC)
					{
					case 'H':sum += tempN * H; break;
					case 'O':sum += tempN * O; break;
					case 'N':sum += tempN * N; break;
					case 'C':sum += tempN* C; break;
					}
				}
				else
					if (tempC != ' ') {
						switch (tempC)
						{
						case 'H':sum += H; break;
						case 'O':sum += O; break;
						case 'N':sum += N; break;
						case 'C':sum += C; break;
						}
					}
				tempN = 0;
				tempC = s[j];
			}
		}
		if (tempN != 0) {
			switch (tempC)
			{
			case 'H':sum += tempN * H; break;
			case 'O':sum += tempN * O; break;
			case 'N':sum += tempN * N; break;
			case 'C':sum += tempN * C; break;
			}
		}
		else
			if (tempC != ' ') {
				switch (tempC)
				{
				case 'H':sum += H; break;
				case 'O':sum += O; break;
				case 'N':sum += N; break;
				case 'C':sum += C; break;
				}
			}
		printf("%.3lf\n", sum);
	}
	return 0;
}

点赞