Challenge: Distance Between Points
Completed
Create a struct Point with double x, y. Read two points (four numbers) and print the distance between them with 2 decimal places. The distance is sqrt((x2 - x1)² + (y2 - y1)²).
Input
x1 y1 x2 y2.
Output
The distance, like 5.00.
Example
Input
0 0 3 4
Output
5.00
Editor
C++
Hints
You can cin straight into members: cin >> a.x >> a.y;
#include <cmath> for sqrt.
Solution explanation
A Point keeps each pair of coordinates together, which makes the function easy to read.
Show solution
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
struct Point {
double x;
double y;
};
double distance(Point a, Point b) {
double dx = b.x - a.x;
double dy = b.y - a.y;
return sqrt(dx * dx + dy * dy);
}
int main() {
Point a, b;
cin >> a.x >> a.y >> b.x >> b.y;
cout << fixed << setprecision(2) << distance(a, b) << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module