Skip to main content

Exercise 2.3: projectile-1.0.cpp

//projectile-1.0.cpp
//Solution to Exercise 2.3

//Program to calculate the time of flight and distance
//travelled by a projectile launched from ground level.
//Reads in magnitude, in m/s, and angle, in degrees,
//of initial velocity from the keyboard.
//Outputs the time of flight and horizontal distance travelled 
//to the screen.
//Steven Bamford

#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  double v_mag;          //initial velocity magnitude (m/s)
  double v_angle_deg, v_angle_rad; //initial velocity angles
  double v_x, v_y;       //and cartesian components
  double t, x;           //time of flight and distance
  const double g = 9.8;  //acc. due to gravity, m/s

  //read in initial velocity parameters
  cout << "Enter the initial velocity parameters:" << endl;
  cout << "Magnitude (m/s): ";
  cin >> v_mag;
  cout << "Angle to the horizontal (degrees): ";
  cin >> v_angle_deg;

  //convert angle to radians
  v_angle_rad = v_angle_deg * M_PI / 180.0;

  //convert velocity to cartesian components
  v_x = v_mag * cos(v_angle_rad);
  v_y = v_mag * sin(v_angle_rad);

  //calculate flight parameters
  t = 2.0 * v_y / g;  //total time of flight
  x = v_x * t;        //total horizontal distance travelled

  //output flight parameters to screen
  cout << endl << "Time of flight = " << t << " seconds"
       << endl << "Total horizontal distance travelled = "
       << x << " metres" << endl;

  system("PAUSE");
  return(0);
}