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 |
#include <iostream> #include <iomanip> // For std::fixed and std::setprecision // Structure to represent a particle struct Particle { double x; // Position in x (meters) double y; // Position in y (meters) double vx; // Velocity in x direction (meters/second) double vy; // Velocity in y direction (meters/second) double ax; // Acceleration in x direction (meters/second^2) double ay; // Acceleration in y direction (meters/second^2) }; // Function to update the particle's position and velocity using Euler's method void updateParticle(Particle& particle, double dt) { particle.vx += particle.ax * dt; particle.vy += particle.ay * dt; particle.x += particle.vx * dt; particle.y += particle.vy * dt; } int main() { Particle particle; double dt; // Time step for simulation int steps; // Number of simulation steps // Input initial conditions std::cout << "Enter the initial x position of the particle (meters): "; std::cin >> particle.x; std::cout << "Enter the initial y position of the particle (meters): "; std::cin >> particle.y; std::cout << "Enter the initial velocity in x direction (meters/second): "; std::cin >> particle.vx; std::cout << "Enter the initial velocity in y direction (meters/second): "; std::cin >> particle.vy; std::cout << "Enter the acceleration in x direction (meters/second^2): "; std::cin >> particle.ax; std::cout << "Enter the acceleration in y direction (meters/second^2): "; std::cin >> particle.ay; std::cout << "Enter the time step for the simulation (seconds): "; std::cin >> dt; std::cout << "Enter the number of simulation steps: "; std::cin >> steps; // Simulation loop std::cout << "Step\tX Position\tY Position" << std::endl; for (int step = 0; step <= steps; ++step) { std::cout << step << "\t" << std::fixed << std::setprecision(2) << particle.x << "\t" << std::fixed << std::setprecision(2) << particle.y << std::endl; updateParticle(particle, dt); } return 0; } |
Explanation:
- Headers and Structure:
- Includes
iostream
for input and output operations andiomanip
for formatting. - Defines the
Particle
structure withx
,y
for position,vx
,vy
for velocity, andax
,ay
for acceleration.
- Includes
- updateParticle Function:
- Updates the particle’s velocity based on its acceleration (
ax
,ay
) and time step (dt
). - Updates the particle’s position based on its velocity and the time step.
- Updates the particle’s velocity based on its acceleration (
- main Function:
- Prompts the user to input the particle’s initial position, velocity, acceleration, time step, and number of simulation steps.
- Runs a simulation loop where it updates the particle’s state and prints its position at each step.