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 |
#include <iostream> #include <cmath> #include <iomanip> class NuclearDecaySimulator { private: double initialAmount; // Initial amount of the substance double decayConstant; // Decay constant (lambda) double timeStep; // Time step for the simulation public: // Constructor NuclearDecaySimulator(double initialAmount, double decayConstant, double timeStep) : initialAmount(initialAmount), decayConstant(decayConstant), timeStep(timeStep) {} // Function to simulate decay over time void simulate(double totalTime) const { int steps = static_cast<int>(totalTime / timeStep); double currentAmount = initialAmount; std::cout << "Time\tAmount Remaining\n"; std::cout << "--------------------------\n"; for (int i = 0; i <= steps; ++i) { double time = i * timeStep; currentAmount = initialAmount * exp(-decayConstant * time); std::cout << std::fixed << std::setprecision(2) << time << "\t" << currentAmount << "\n"; } } }; int main() { double initialAmount, decayConstant, timeStep, totalTime; // Input parameters std::cout << "Enter the initial amount of the substance: "; std::cin >> initialAmount; std::cout << "Enter the decay constant (lambda): "; std::cin >> decayConstant; std::cout << "Enter the time step for the simulation: "; std::cin >> timeStep; std::cout << "Enter the total time for the simulation: "; std::cin >> totalTime; // Create a simulator object NuclearDecaySimulator simulator(initialAmount, decayConstant, timeStep); // Run the simulation simulator.simulate(totalTime); return 0; } |
Explanation
- Class Definition:
NuclearDecaySimulator
class holds the parameters for the simulation:initialAmount
(the initial quantity of the substance),decayConstant
(the decay rate), andtimeStep
(the granularity of time steps in the simulation).
- Constructor:
- Initializes the parameters of the simulation.
simulate
Method:- Computes and displays the amount of substance remaining over time.
- Uses the formula N(t)=N0⋅e−λtN(t) = N_0 \cdot e^{-\lambda t}, where N(t)N(t) is the amount remaining at time tt, N0N_0 is the initial amount, and λ\lambda is the decay constant.
- Main Function:
- Prompts the user to input the parameters.
- Creates a
NuclearDecaySimulator
object with the user-provided parameters. - Calls the
simulate
method to display the decay simulation results.