Answer to Question #99403 in C++ for Caleb

Question #99403
Determine the distance between point (x1, y1) and point (x2, y2), and assign the result to pointsDistance. The calculation is using the distance formula.

Ex: For points (1.0, 2.0) and (1.0, 5.0), pointsDistance is 3.0.
1
Expert's answer
2019-11-28T09:03:54-0500
/*************************************************************************/
/**                             Q99403                                   */
/**          The distance between points on the coordinate plane.        */
/*************************************************************************/
#include <iostream>
#include <cmath>

using namespace std;

double inputDouble(string);     // Input from the console of type double. Check for simple input errors.

int main()
{
  /* The coordinates of the point. Structure.*/
    struct Point                
    {
        double x;
        double y;
    };

    Point p1, p2;               // Declare two points.

    cout << "Please enter the coordinates of the first point." << endl;

    /* Enter the coordinates of the points. */
    p1.x = inputDouble("x1 = ");
    p1.y = inputDouble("y1 = ");
    p2.x = inputDouble("x2 = ");
    p2.y = inputDouble("y2 = ");

    /* We use the formula to calculate the distance between points. Output the result. */
    cout << endl<< "For points (" << (double)p1.x << ", " << p1.y << ") and (" << p2.x << ", " << p2.y;
    cout << "), pointsDistance is " << sqrt((pow((p2.x-p1.x),2))+(pow((p2.y-p1.y),2))) << "." << endl;
    return 0;
}


/** Function for entering a value of type "double" with validation.*/
/** The string in the argument is needed to prompt for data entry. */
double inputDouble(string s)
{
    double d;
    do{
      cout << s;
      cin >> d;
      if(!cin)                //If incorrect characters are entered, then clear the input buffer and ask to enter again.
      {
        cout << "The input is not correct. Try again.\n";
        cin.clear();
        while (cin.get() != '\n');
      }
      else break;
    }while(true);

    return d;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS