分析:
1. **讀取輸入**:首先,我們需要讀取輸入中的第一行,了解有多少個化學式需要處理。之后,對于每個化學式,我們逐行讀取并進行處理。
2. **解析化學式**:對于每個化學式,我們需要遍歷其字符串,識別出元素(C, H, O, N)及其后可能跟隨的數字(表示該元素的數量)。如果元素后沒有數字,則默認數量為1。
3. **計算分子量**:通過查找每個元素對應的原子量(C: 12.01 g/mol, H: 1.008 g/mol, O: 16.00 g/mol, N: 14.01 g/mol),并乘以該元素的數量,我們可以計算出每個元素的總質量。將所有元素的總質量相加,得到整個化學式的分子量。
4. **輸出結果**:對于每個化學式,計算完成后輸出其分子量,保留三位小數。
代碼實現:
#include <iostream>
#include <string>
#include <map>
#include <iomanip>using namespace std;// Function to calculate the mass of a chemical formula
double calculateMass(const string& formula, const map<char, double>& atomicMasses) {double totalMass = 0.0;int i = 0;while (i < formula.length()) {char element = formula[i];int quantity = 0; // Initialize quantity to 0i++;// Loop to calculate the quantity of the current elementwhile (i < formula.length() && isdigit(formula[i])) {quantity = quantity * 10 + (formula[i] - '0');i++;}// If quantity is still 0, it means there was no number after the element, so set it to 1if (quantity == 0) {quantity = 1;}// Add the mass of the current element to the total masstotalMass += atomicMasses.at(element) * quantity;}return totalMass;
}int main() {int T;cin >> T;// Map to store the atomic masses of the elementsmap<char, double> atomicMasses = {{'C', 12.01},{'H', 1.008},{'O', 16.00},{'N', 14.01}};while (T--) {string formula;cin >> formula;cout << setprecision(3) << fixed << calculateMass(formula, atomicMasses) << endl;}return 0;
}
這段代碼通過定義一個`calculateMass`函數來處理核心邏輯,該函數接受一個化學式字符串和一個元素原子量的映射表作為參數。通過遍歷化學式字符串,識別元素及其數量,并利用映射表查找對應的原子量進行計算,最終得到化學式的總分子量。`main`函數中,首先讀取案例數量,然后對每個化學式調用`calculateMass`函數進行處理,并輸出結果。通過使用`setprecision`和`fixed`,確保輸出的分子量保留三位小數,滿足題目要求。