78.7k views
3 votes
(5 points) Create a user-defined data structure (i.e., struct) called Point that represents a two-dimensional Cartesian coordinate (x, y). The member variables of this struct will be just x and y, which are both floating-point values. (5 points) Define a function called calculateDistance that takes two parameters, each of type Point* (i.e., pointer to Point) and returns the distance between the two given points. As you may recall, the formula for calculating the distance between two points, say p1(x1, y1) and p2(x2, y2) is:

User Gav
by
3.6k points

1 Answer

2 votes

Answer:

Here is the C++ program:

#include<iostream> //to use input output functions

#include <math.h> //to use sqrt and pow function

#include<iomanip> //to use setprecision

using namespace std; //to identify objects cin cout

struct Point { // structure name

float x,y; // member variables

};

float calculateDistance (Point a, Point b) { //function that that takes two parameters of type Point

float distance; //stores the distance between two points

distance=sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2)); //formula to compute distance between two points

return distance; } //returns the computed distance

int main() { //start of main function

Point p1,p2; //creates objects of Point

cout<<"Enter point 1 coordinates: "<<endl; //prompts user to enter the value for coordinates of first point

cin>>p1.x; //reads input value of x coordinate of point 1 (p1)

cin>>p1.y; //reads y coordinate of point 1 (p1)

cout<<"Enter point 2 coordinates: "<<endl; //prompts user to enter the value for coordinates of second point

cin>>p2.x; //reads input value of x coordinate of point 2 (p2)

cin>>p2.y; //reads y coordinate of point 2 (p2)

cout<<"The distance between two points is "<<fixed<<setprecision(2)<<calculateDistance(p1,p2);} //calls function by passing p1 and p2 to compute the distance between p1 and p2 and display the result (distance) up to 2 decimal places

Step-by-step explanation:

The program has a structure named Point that represents a two-dimensional Cartesian coordinate (x, y). The member variables of this struct are x and y, which are both floating-point values. A function called calculateDistance takes two parameters, a and b of type Pointer and returns the distance between the two given points using formula:


\sqrt{(x_(2)-x_(1) )^(2) +(y_(2)-y_(1) )^(2) }

It uses pow function to compute the power of 2 and sqrt function to compute the square root.

Then in main() method the program prompts the user to enter coordinates for two points and calls calculateDistance method to compute the distance between two points and display the result up to 2 decimal places using setprecision(2).

The program along with the output is attached in a screenshot.

(5 points) Create a user-defined data structure (i.e., struct) called Point that represents-example-1
User Jszobody
by
4.1k points