#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    16
    Rep Power
    0

    Program to calculate distance...


    Here I am with another problem question...

    I am writing a program to calculate the distance between two points. This is the code I have so far, but it isn't working. I'm having trouble sorting out what variable name to put where. :/ Can someone point me in the correct direction?
    Code:
    #include <stdio.h>
    #include <math.h>
    
    struct point
    {
      float x;
      float y;
    };
    
    float distance(struct point, struct point);
    void enter_a_point(struct point *);
    
    int main(void)
    {
      struct point p1, p2;
    
      enter_a_point(x,y);
      enter_a_point(x,y);
    
      printf("Distance between the points = %.2f\n", distance(struct point p1, struct point p2));
    
      return 0;
    }
    
    float distance(struct point p1, struct point p2)
    {
      return sqrt(pow(p2[x]-p1[x],2) + pow(p2[y]-p1[y],2));
    }
    
    void enter_a_point(struct point *p)
    {
      printf("\nEnter an x coordinate: ");
      scanf("%f", &x);
    
      printf("\nEnter a y coordinate: ");
      scanf("%f", &y);
    }
    Thank you!
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,220
    Rep Power
    2222
    Code:
    float distance(struct point p1, struct point p2)
    {
      return sqrt(pow(p2[x]-p1[x],2) + pow(p2[y]-p1[y],2));
    }
    What's x? What's y? Where are they declared and where are they initialized?

    And why are you treating p1 and p2 as if they were arrays?

    Code:
    void enter_a_point(struct point *p)
    {
      printf("\nEnter an x coordinate: ");
      scanf("%f", &x);
    
      printf("\nEnter a y coordinate: ");
      scanf("%f", &y);
    }
    Again, what's x and what's y and where are they declared? And why, after passing in point, you don't use it?

    You access a field within a struct with dot notation. Like PersRec.name . But that only works if you have the struct itself. If you are using a pointer to a struct, eg pPersRec, then you use an arrow; eg pPersRec->name .

    When in doubt, read your book.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    16
    Rep Power
    0

    Thank you!!!


    I got it working! Thank you for the help. :)
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481
    I'd use the hypot function,

    distance = hypot(x1-x0, y1-y0);
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo