620
Calculer la distance entre deux points
- #include <stdio.h>
- #include <math.h>
- struct point {
- int x;
- int y;
- };
- double dist( struct point pt1, struct point pt2 ) {
- int dx = pt2.x - pt1.x;
- int dy = pt2.y - pt1.y;
- return sqrt( dx*dx + dy*dy );
- }
- main( ) {
- struct point pt1 = { 0, 0 };
- struct point pt2 = { 3, 4 };
- struct point pt3 = { -3, -4 };
- /* don't forget to include math.h */
- printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt1.x, pt1.y, pt2.x, pt2.y, dist( pt1, pt2 ));
- printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt2.x, pt2.y, pt1.x, pt1.y, dist( pt2, pt1 ));
- printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt2.x, pt2.y, pt3.x, pt3.y, dist( pt2, pt3 ));
- printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt3.x, pt3.y, pt2.x, pt2.y, dist( pt3, pt2 ));
- printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt3.x, pt3.y, pt3.x, pt3.y, dist( pt3, pt3 ));
- printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt1.x, pt1.y, pt1.x, pt1.y, dist( pt1, pt1 ));
- }
$ gcc -DSTANDALONE -o points -lm points.c
$ ./points
[0, 0] <-> [3, 4] = 5.0
[3, 4] <-> [0, 0] = 5.0
[3, 4] <-> [-3, -4] = 10.0
[-3, -4] <-> [3, 4] = 10.0
[-3, -4] <-> [-3, -4] = 0.0
[0, 0] <-> [0, 0] = 0.0
Commentaires