7

Compute the distance between two points

  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. struct point {
  5.     int x;
  6.     int y;
  7. };
  8.  
  9. double dist( struct point pt1, struct point pt2 ) {
  10.     int dx = pt2.x - pt1.x;
  11.     int dy = pt2.y - pt1.y;
  12.  
  13.     return sqrt( dx*dx + dy*dy );
  14. }
  15.  
  16. main( ) {
  17.     struct point pt1 = { 0, 0 };
  18.     struct point pt2 = { 3, 4 };
  19.     struct point pt3 = { -3, -4 };
  20.  
  21.     /* don't forget to include math.h */
  22.     printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt1.x, pt1.y, pt2.x, pt2.y, dist( pt1, pt2 ));
  23.     printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt2.x, pt2.y, pt1.x, pt1.y, dist( pt2, pt1 ));
  24.     printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt2.x, pt2.y, pt3.x, pt3.y, dist( pt2, pt3 ));
  25.     printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt3.x, pt3.y, pt2.x, pt2.y, dist( pt3, pt2 ));
  26.     printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt3.x, pt3.y, pt3.x, pt3.y, dist( pt3, pt3 ));
  27.     printf("[%d, %d] <-> [%d, %d] = %.1f\n", pt1.x, pt1.y, pt1.x, pt1.y, dist( pt1, pt1 ));
  28. }
$ 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

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].