#include #include const double g = 9.8; // metres/sec double compute_distance (double angle /* in degrees */, double initial_velocity /* in m/s */, double height /* in m */ ) { double angle_radians = angle * (M_PI / 180.0), vel_v, vel_h; // vertical and horizontal components of initial velocity vel_v = sin(angle_radians) * initial_velocity; vel_h = cos(angle_radians) * initial_velocity; return ( ( vel_v + sqrt ((vel_v * vel_v) + (2 * g * height)) ) / g ) * vel_h; } void compute_and_output (double min_velocity, double max_velocity, double height, double angle, double distance) { double low, high, mid, computed_distance; // make sure that we can hit the target if (distance < compute_distance (angle, min_velocity, height)) { cout << "\nTarget is too close to be hit.\n"; return; } if (distance > compute_distance (angle, max_velocity, height)) { cout << "\nTarget is too far away to be hit.\n"; return; } low = min_velocity; high = max_velocity; for (;;) { mid = (high + low) / 2; if ((high - low) < 0.0002) { // velocity is within 0.0001 of the correct answer cout << "\nA velocity of " << mid << " m/s should work fine.\n" << "This velocity is within 0.0001 of the theoretical value.\n"; return; } computed_distance = compute_distance (angle, mid, height); if (fabs(computed_distance - distance) < 0.001) { // distance within 0.01 of desired distance cout << "\nA velocity of " << mid << " m/s will do nicely.\n" << "This will put you within 0.001 m of the target.\n"; return; } if (computed_distance > distance) { high = mid; } else { low = mid; } } } void main (void) { double angle, min_velocity, max_velocity, launch_height, target_height, distance; cout << "Welcome to the CAT-1 artillery control system!\n" << "\nPlease enter your minium and maximum launch velocities: (in m/s): "; cin >> min_velocity >> max_velocity; cout << "Please enter height of release point (in m): "; cin >> launch_height; cout << "Please enter release angle (in degrees from the horizontal: "; cin >> angle; cout << "\nThank you - the system is now calibrated for your installation.\n"; for (;;) { cout << "\nEnter distance to target and target height (zeroes to stop): "; cin >> distance >> target_height; if ((distance == 0) && (target_height == 0)) { return; } if (distance <= 0) { cout << "\nSorry - distance must be > 0.\n"; } else if (target_height > launch_height) { cout << "Sorry - target height must be <= the launch height.\n"; } else { compute_and_output (min_velocity, max_velocity, launch_height - target_height, angle, distance); } } }