1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
#include <iostream> #include <iomanip> // Constants const double INITIAL_A = 100.0; // Initial concentration of A const double INITIAL_B = 50.0; // Initial concentration of B const double REACTION_RATE = 0.1; // Reaction rate constant const double TIME_STEP = 0.1; // Time step for simulation const int STEPS = 100; // Number of simulation steps // ChemicalReaction class class ChemicalReaction { public: ChemicalReaction(double a, double b, double rate) : concentrationA(a), concentrationB(b), rate(rate) {} void simulateStep() { double deltaC = rate * concentrationA * concentrationB * TIME_STEP; concentrationA -= deltaC; concentrationB -= deltaC; concentrationC += deltaC; // Ensure concentrations do not go negative if (concentrationA < 0) concentrationA = 0; if (concentrationB < 0) concentrationB = 0; } void printStatus(double time) const { std::cout << "Time: " << std::fixed << std::setprecision(1) << time << " A: " << std::fixed << std::setprecision(2) << concentrationA << " B: " << std::fixed << std::setprecision(2) << concentrationB << " C: " << std::fixed << std::setprecision(2) << concentrationC << std::endl; } private: double concentrationA; // Concentration of chemical A double concentrationB; // Concentration of chemical B double concentrationC = 0.0; // Concentration of chemical C (product) double rate; // Reaction rate constant }; int main() { ChemicalReaction reaction(INITIAL_A, INITIAL_B, REACTION_RATE); std::cout << "Simulation of Chemical Reaction:" << std::endl; std::cout << "Initial Conditions:" << std::endl; reaction.printStatus(0.0); for (int step = 1; step <= STEPS; ++step) { reaction.simulateStep(); double time = step * TIME_STEP; reaction.printStatus(time); } return 0; } |
Explanation:
- ChemicalReaction Class:
concentrationA
: The current concentration of chemical A.concentrationB
: The current concentration of chemical B.concentrationC
: The current concentration of the product C.rate
: The reaction rate constant.ChemicalReaction(double a, double b, double rate)
: Constructor to initialize the concentrations and rate.simulateStep()
: Updates the concentrations based on the reaction rate and time step. The amount of product formed (deltaC
) is calculated and subtracted from the reactants.printStatus(double time) const
: Prints the current status of the concentrations and time.
AdvertisementAdvertisementAdvertisement - Main Function:
- Initializes the
ChemicalReaction
object with initial concentrations and reaction rate. - Prints the initial status.
- Simulates the reaction over a specified number of steps, updating and printing the concentrations at each step.
- Initializes the