Exercise 4.1: projectile-2.0.cpp
//projectile-2.0.cpp
//Solution to Exercise 4.1
//Adapts projectile-1.0.cpp to read and write to files
//instead of the console.
//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 a file named projectile_data.in
//Outputs the time of flight and horizontal distance travelled
//to a file named projectile_data.out
//Steven Bamford
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <fstream>
#include <iomanip>
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
ifstream fin; //input data file stream
ofstream fout; //output data file stream
//open files
fin.open("projectile_data.in");
fout.open("projectile_data.out");
//loop through data
while (true)
{
//read initial velocity parameters
fin >> v_mag >> v_angle_deg;
//break if end of file reached
if (fin.eof()) break;
//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
fout.setf(ios::fixed, ios::floatfield);
fout.precision(2);
fout << t << " " << setw(8) << x << endl;
}
//close files
fin.close();
fout.close();
return(0);
}