Question 2
Back to Exercise
Represent a point as a structure and write a function that returns the distance between two points.
Solution
#include <math.h>
#include <stdio.h>
struct point {
double x, y;
};
double distance(struct point a, struct point b) {
return hypot(b.x - a.x, b.y - a.y); /* sqrt(dx*dx + dy*dy), without overflow */
}
int main(void) {
struct point p = {1, 2}, q = {4, 6};
printf("distance = %.2f\n", distance(p, q));
return 0;
}
distance = 5.00
dx = 3 and dy = 4, so the distance is 5. hypot() from <math.h> computes √(dx² + dy²) without overflowing for large values. On Linux, link with -lm.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!