Distance between 2 Points: Mrs. Anitha , our favourite Maths teacher wanted to teach her new batch students to find the distance between 2 points.
Write a program to accept 2 points and to calculate the distance between them using functions and pointers.
Function Specification:
float distance(int *x1, int *y1, int *x2, int *y2)
This function returns the distance between two points.
Input Format:
Input consists of 4 integers.
The first 2 integers refer to x and y coordinate of Point 1
The next 2 integers refer to x and y coordinate of Point 2
Output Format:
The output consists of 1 float. Display the output correct to 2 decimal places.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input and Output:
Enter x1
2
Enter y1
3
Enter x2
4
Enter y2
1
Distance between 2 points is 2.83
Function Definitions:
float distance (int *, int *, int *, int *) |
Solution
#include <iostream>
#include <cmath>
using namespace std;
float distance(int *x1, int *y1, int *x2, int *y2)
{
float d;
d = sqrt((*x2 - *x1) * (*x2 - *x1) + (*y2 - *y1) * (*y2 - *y1));
return d;
}
int main()
{
int x1, y1, x2, y2;
cout << "Enter x1\n";
cin >> x1;
cout << "Enter y1\n";
cin >> y1;
cout << "Enter x2\n";
cin >> x2;
cout << "Enter y2\n";
cin >> y2;
printf("Distance between 2 points is %.2f\n",distance(&x1, &y1, &x2, &y2));
return 0;
}
Happy Learning – If you require any further information, feel free to contact me.