/* * Contrived example of using "struct" to represent 2d point: * Define and demo/test some simple functions. */ #include #include /* point in 2d space */ typedef struct point2d { double x; double y; } point2d_t; /* function declarations -- descriptions with definitions below */ double distance(point2d_t p1, point2d_t p2); double square(double d); void scale(point2d_t *p, double factor); void test_distance(point2d_t p1, point2d_t p2); void test_scale(point2d_t p, double f); /* main program */ int main(void) { point2d_t p1 = { 1.0, 1.0 }; point2d_t p2 = { 4.0, 5.0 }; point2d_t p3 = { 1.0, -1.0 }; test_distance(p1, p2); test_distance(p1, p3); test_scale(p2, 2.0); test_scale(p2, -10.0); return 0; } /* convenience/"helper" function for distance() */ double square(double d) { return d*d; } /* * get distance between two points */ double distance(point2d_t p1, point2d_t p2) { return sqrt(square(p1.x - p2.x) + square(p1.y - p2.y)); } /* * "scale" point -- multiply coordinates by scalar factor * modifies p */ void scale(point2d_t *p, double factor) { (p->x) *= factor; (p->y) *= factor; } /* * test/demo distance function -- call and print input/output nicely */ void test_distance(point2d_t p1, point2d_t p2) { printf("distance between (%g, %g) and (%g, %g) is %g\n", p1.x, p1.y, p2.x, p2.y, distance(p1, p2)); } /* * test/demo scale function -- call and print input/output nicely */ void test_scale(point2d_t p, double f) { /* create a copy so we can print both "before" and "after" easily */ point2d_t temp_p = p; scale(&temp_p, f); printf("(%g, %g) scaled by %g is (%g, %g)\n", p.x, p.y, f, temp_p.x, temp_p.y); }