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 |
#include <iostream> #include <cmath> #include <iomanip> const double GRAVITY = 9.81; // Acceleration due to gravity (m/s^2) // Function to simulate projectile motion void simulateProjectile(double velocity, double angle, double timeStep, int numSteps) { double angleRad = angle * M_PI / 180.0; // Convert angle to radians double initialX = 0.0; // Initial x position double initialY = 0.0; // Initial y position double velocityX = velocity * cos(angleRad); // Initial x velocity double velocityY = velocity * sin(angleRad); // Initial y velocity std::cout << "Time (s)\tX (m)\tY (m)\n"; std::cout << std::fixed << std::setprecision(2); for (int step = 0; step <= numSteps; ++step) { double time = step * timeStep; double x = initialX + velocityX * time; double y = initialY + velocityY * time - 0.5 * GRAVITY * time * time; // Check if the projectile has hit the ground if (y < 0) { y = 0; std::cout << time << "\t" << x << "\t" << y << " (Ground)\n"; break; } std::cout << time << "\t" << x << "\t" << y << "\n"; } } int main() { double velocity, angle, timeStep; int numSteps; std::cout << "Enter the initial velocity (m/s): "; std::cin >> velocity; std::cout << "Enter the launch angle (degrees): "; std::cin >> angle; std::cout << "Enter the time step (s): "; std::cin >> timeStep; std::cout << "Enter the number of steps: "; std::cin >> numSteps; std::cout << "Projectile Motion Simulation\n"; simulateProjectile(velocity, angle, timeStep, numSteps); return 0; } |
Explanation
- Constants:
- GRAVITY: The acceleration due to gravity (9.81 m/s²).
- Function
simulateProjectile(double velocity, double angle, double timeStep, int numSteps)
:- Purpose: Simulates the trajectory of a projectile.
- Parameters:
velocity
: Initial velocity of the projectile (m/s).angle
: Launch angle of the projectile (degrees).timeStep
: Time interval between each step of the simulation (s).numSteps
: Number of time steps to simulate.
- Implementation:
- Converts the launch angle from degrees to radians.
- Calculates the initial x and y components of velocity.
- Computes and prints the position of the projectile at each time step.
- Stops the simulation if the projectile hits the ground (y < 0).
- Main Function:
- Setup: Prompts the user for the initial velocity, launch angle, time step, and number of steps.
- Simulation: Calls
simulateProjectile
to compute and display the projectile’s trajectory.
Usage
- Projectile Motion Simulation: Provides a visual representation of a projectile’s trajectory based on its initial velocity and launch angle.
- Trajectory Analysis: Helps understand how different parameters affect the motion of a projectile.