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 quantity of the radioactive 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 from the user 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 NuclearDecaySimulator object NuclearDecaySimulator simulator(initialAmount, decayConstant, timeStep); // Run the simulation simulator.simulate(totalTime); return 0; } |
Explanation
- Class Definition (
NuclearDecaySimulator
):- Private Members:
initialAmount
: Initial quantity of the radioactive substance.decayConstant
: Decay constant (λ), which describes the rate of decay.timeStep
: Interval of time between calculations in the simulation.
- Private Members:
- Constructor:
- Initializes the simulation parameters with provided values.
simulate
Method:- Calculates and prints the amount of the substance remaining over time.
- Computes the remaining amount using the formula N(t)=N0⋅e−λtN(t) = N_0 \cdot e^{-\lambda t}, where N(t)N(t) is the amount at time tt, N0N_0 is the initial amount, and λ\lambda is the decay constant.
- Loops through each time step, updating and displaying the amount remaining.
main
Function:- Prompts the user to input values for the initial amount, decay constant, time step, and total time.
- Creates an instance of
NuclearDecaySimulator
with the user’s parameters. - Calls the
simulate
method to output the decay simulation results over the specified total time.